Created
October 14, 2013 22:08
-
-
Save anupsavvy/6983050 to your computer and use it in GitHub Desktop.
1) Find the maximum sum possible from picking a contiguous subsequence of an array. [-1, 5, 6, -2, 20, -50, 4]
What is the largest sum of contiguous elements available in this list?
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
public int largestSum(int[] A){ | |
if(A.length == 0) return 0; | |
if(A.length == 1) return A[0]; | |
int max = Integer.MIN_VALUE; | |
int curr = 0; | |
for(int i = 0; i < A.length; i++){ | |
curr += A[i]; | |
if(curr < 0){ | |
curr = 0; | |
}else if(curr > max){ | |
max = curr; | |
} | |
} | |
return max; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment