Last active
May 29, 2022 17:55
-
-
Save woodRock/2d76e212984831e559c2ad7e6121f669 to your computer and use it in GitHub Desktop.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-up: Can you do this in O(N) time and constant space?
This file contains 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
class LargestSum { | |
public static int get_sum(int[] arr, int n){ | |
int incl = arr[0]; // Max sum including the previous element | |
int excl = 0; // Max sum excluding the previous element | |
int excl_new; | |
int i; | |
for (i=0; i<n; i++){ | |
/* current max excluding i */ | |
excl_new = (incl>excl) ? incl:excl; | |
/* current max inlcuding i */ | |
incl = excl + arr[i]; | |
excl = excl_new; | |
} | |
return ((incl>excl) ? incl:excl); | |
} | |
public static void main(String [] args){ | |
int[] array = {2,4,6,2,5}; | |
System.out.print(get_sum(array, array.length)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have an error in the code, you should change the i=0 to i=1 in the for loop.
You can see the error if you check the method on [5, 1, 1, 5] array, the output should be 10 and its 11.