|
| 1 | +// Apporach 1 : Left to Right Approach |
| 2 | +class Solution { |
| 3 | + public: |
| 4 | + // Recursive function to solve the problem |
| 5 | + int solve(vector<int>& arr, int i, int n){ |
| 6 | + // Base case: If the index exceeds the size of the array, return 0 (no more elements to pick) |
| 7 | + if(i > n) return 0; |
| 8 | + |
| 9 | + // Base case: If we reach the last element, return its value |
| 10 | + if(i == n) return arr[i]; |
| 11 | + |
| 12 | + // Option 1: Include the current element arr[i] and move two steps forward (i+2) |
| 13 | + int include = solve(arr, i+2, n) + arr[i]; |
| 14 | + |
| 15 | + // Option 2: Exclude the current element arr[i] and move one step forward (i+1) |
| 16 | + int exclude = solve(arr, i+1, n) + 0; // Adding 0 doesn't affect the result |
| 17 | + |
| 18 | + // Return the maximum sum between including and excluding the current element |
| 19 | + return max(include, exclude); |
| 20 | + } |
| 21 | + |
| 22 | + // Function to find the maximum sum without adjacent elements |
| 23 | + int findMaxSum(vector<int>& arr) { |
| 24 | + int n = arr.size(); // Get the size of the array |
| 25 | + |
| 26 | + // Start the recursive process from index 0 |
| 27 | + int sum = solve(arr, 0, n-1); |
| 28 | + |
| 29 | + return sum; // Return the maximum sum obtained |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +// Approach 2 : Right to Left Approach |
| 34 | +class Solution { |
| 35 | + public: |
| 36 | + // Recursive function to solve the problem |
| 37 | + int solve(vector<int>& arr, int n){ |
| 38 | + // Base case: If n is negative, we return 0 (no more elements to pick) |
| 39 | + if(n < 0) return 0; |
| 40 | + |
| 41 | + // Base case: If n is 0, return the first element |
| 42 | + if(n == 0) return arr[0]; |
| 43 | + |
| 44 | + // Option 1: Include the current element arr[n] and move two steps back (n-2) |
| 45 | + int include = solve(arr, n-2) + arr[n]; |
| 46 | + |
| 47 | + // Option 2: Exclude the current element arr[n] and move one step back (n-1) |
| 48 | + int exclude = solve(arr, n-1) + 0; // Adding 0 doesn't affect the result |
| 49 | + |
| 50 | + // Return the maximum sum between including and excluding the current element |
| 51 | + return max(include, exclude); |
| 52 | + } |
| 53 | + |
| 54 | + // Function to find the maximum sum without adjacent elements |
| 55 | + int findMaxSum(vector<int>& arr) { |
| 56 | + int n = arr.size(); // Get the size of the array |
| 57 | + |
| 58 | + // Start the recursive process from the last index (n-1) |
| 59 | + int sum = solve(arr, n-1); |
| 60 | + |
| 61 | + return sum; // Return the maximum sum obtained |
| 62 | + } |
| 63 | +}; |
| 64 | + |
| 65 | + |
0 commit comments