|
| 1 | +// User function template for C++ |
| 2 | +class Solution { |
| 3 | + public: |
| 4 | + // Recursive function to solve the problem with memoization |
| 5 | + int solve(vector<int>& arr, int i, int n, vector<int>& dp){ |
| 6 | + // Base case: If the index i is out of bounds, return 0 (no more elements to pick) |
| 7 | + if(i >= arr.size()) return 0; |
| 8 | + |
| 9 | + // If the result for the current index i is already computed, return it from the memoization table |
| 10 | + if(dp[i] != -1) return dp[i]; |
| 11 | + |
| 12 | + // Option 1: Include the current element arr[i] in the sum, |
| 13 | + // then move 2 steps forward (i+2) to ensure no adjacent elements are selected |
| 14 | + int include = solve(arr, i+2, n, dp) + arr[i]; |
| 15 | + |
| 16 | + // Option 2: Exclude the current element arr[i] from the sum, |
| 17 | + // then move 1 step forward (i+1) to check the next element |
| 18 | + int exclude = solve(arr, i+1, n, dp) + 0; // Adding 0 doesn't affect the result |
| 19 | + |
| 20 | + // Store the maximum sum of including or excluding the current element in the dp array |
| 21 | + dp[i] = max(include, exclude); |
| 22 | + |
| 23 | + // Return the computed result for the current index i |
| 24 | + return dp[i]; |
| 25 | + } |
| 26 | + |
| 27 | + // Function to find the maximum sum without adjacent elements |
| 28 | + int findMaxSum(vector<int>& arr) { |
| 29 | + int n = arr.size(); // Get the size of the input array |
| 30 | + |
| 31 | + // Initialize the memoization array dp with -1 to indicate uncomputed results |
| 32 | + // dp[i] will store the maximum sum starting from index i |
| 33 | + vector<int> dp(n+1, -1); |
| 34 | + |
| 35 | + // Start the recursive process from index 0 |
| 36 | + int sum = solve(arr, 0, n-1, dp); |
| 37 | + |
| 38 | + // Return the maximum sum obtained |
| 39 | + return sum; |
| 40 | + } |
| 41 | +}; |
0 commit comments