Last active
December 25, 2015 12:49
-
-
Save ssk2/6979550 to your computer and use it in GitHub Desktop.
MaxConsecutiveSum solution in linear time for Coding For Interviews.
http://codingforinterviews.com/
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
package cfi.maxconsecutivesum; | |
public class MaxConsecutiveSum { | |
public static void main(String[] args) { | |
int[] input = new int[] { -1, 5, 6, -2, 20, -50, 4 }; | |
System.out.println(getMaxConsecutiveSumLinear(input)); | |
} | |
public static int getMaxConsecutiveSumLinear(int[] input) { | |
// initialise to the first value instead of Integer.MIN_VALUE | |
// since there is a risk we'll underflow | |
int prevMax = input[0]; | |
int maxSum = prevMax; | |
for (int i = 1; i < input.length; i++) { | |
if (input[i] > prevMax + input[i]) | |
prevMax = input[i]; // throw away history | |
else | |
prevMax += input[i]; | |
if (prevMax > maxSum) | |
maxSum = prevMax; | |
} | |
return maxSum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 12 is indentation madness! :)