Created
April 24, 2014 05:52
-
-
Save gabhi/11242984 to your computer and use it in GitHub Desktop.
Largest Continuous Sum of an Array
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 Integer findSum(int[] arr) { | |
if (arr.length == 0) | |
return null; | |
int largestSum = arr[0]; | |
int currentSum = arr[0]; | |
for (int i = 1; i < arr.length; i++) { | |
currentSum = max(currentSum + arr[i], arr[i]); // if the current sum gets negative, we reset it | |
largestSum = max(currentSum, largestSum); | |
} | |
return largestSum; | |
} | |
private int max(int first, int second) { | |
return first > second ? first : second; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment