Created
July 2, 2021 11:52
-
-
Save vineethm1627/df91ebb598a9470898b2e9a0e2a6dfd5 to your computer and use it in GitHub Desktop.
O(1) Space efficient solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Function to return the maximum sum without adding adjacent elements. | |
// include/ exclude DP | |
long long maximumSum(int arr[], int sizeOfArray) { | |
//Your code here | |
// edge case: if all the elements are negative | |
bool flag = true; | |
int max_val = INT_MIN; | |
for(int i = 0; i < sizeOfArray; i++) { | |
if(arr[i] > 0) { | |
flag = false; | |
break; | |
} | |
if(arr[i] > max_val) | |
max_val = arr[i]; | |
} | |
// all negative values are there | |
if(flag) | |
return max_val; | |
long long prev_incl = arr[0], prev_excl = 0; | |
long long cur_incl, cur_excl; | |
for(int i = 1; i < sizeOfArray; i++) { | |
cur_incl = prev_excl + arr[i]; | |
cur_excl = max(prev_incl, prev_excl); | |
// update values for next iteration | |
prev_incl = cur_incl; | |
prev_excl = cur_excl; | |
} | |
return max(cur_incl, cur_excl); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment