Skip to content

Instantly share code, notes, and snippets.

@ssk2
Last active December 25, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssk2/6979550 to your computer and use it in GitHub Desktop.
Save ssk2/6979550 to your computer and use it in GitHub Desktop.
MaxConsecutiveSum solution in linear time for Coding For Interviews. http://codingforinterviews.com/
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;
}
}
@bcjordan
Copy link

Line 12 is indentation madness! :)

@ssk2
Copy link
Author

ssk2 commented Oct 14, 2013

Haha, fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment