File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
24 - Dynamic Programming Problems/06 - Max Sum without Adjacents Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ // User function template for C++
2+ class Solution {
3+ public:
4+ // Function to find the maximum sum without adjacent elements using space-optimized DP
5+ int solve (vector<int >& arr){
6+ int n = arr.size (); // Get the size of the input array
7+
8+ // Initialize the two variables to store the previous two results
9+ int prev2 = 0 ; // prev2 stores the maximum sum up to index i-2
10+ int prev1 = arr[0 ]; // prev1 stores the maximum sum up to index i-1 (initially, it's the first element)
11+
12+ // Iterate through the array starting from the second element
13+ for (int i = 1 ; i < n; i++){
14+ // Option 1: Include the current element arr[i]
15+ int include = prev2 + arr[i];
16+
17+ // Option 2: Exclude the current element arr[i]
18+ int exclude = prev1; // We just carry forward prev1 as it's the maximum sum up to the previous index
19+
20+ // The result for the current index i is the maximum of include and exclude options
21+ int ans = max (include, exclude);
22+
23+ // Update prev2 and prev1 for the next iteration
24+ prev2 = prev1; // prev2 moves to prev1
25+ prev1 = ans; // prev1 stores the maximum sum for the current index
26+ }
27+
28+ // The final answer is stored in prev1 (which is the maximum sum for the entire array)
29+ return prev1;
30+ }
31+
32+ // Main function to find the maximum sum
33+ int findMaxSum (vector<int >& arr) {
34+
35+ // Call the solve function and get the result
36+ int sum = solve (arr);
37+
38+ // Return the maximum sum
39+ return sum;
40+ }
41+ };
You can’t perform that action at this time.
0 commit comments