Skip to content

Instantly share code, notes, and snippets.

@felipernb
Created August 21, 2012 07:13
Show Gist options
  • Select an option

  • Save felipernb/3413011 to your computer and use it in GitHub Desktop.

Select an option

Save felipernb/3413011 to your computer and use it in GitHub Desktop.
Maximum Subarray
package com.feliperibeiro;
import java.util.Arrays;
public class MaximumSubarray {
public int[] max(int[] a) {
int maxSum = 0,
currentSum = 0,
maxSumStart = 0,
maxSumEnd = 0,
currentSumStart = 0;
for (int currentSumEnd = 0; currentSumEnd < a.length; currentSumEnd++) {
currentSum += a[currentSumEnd];
if (currentSum > maxSum) {
maxSum = currentSum;
maxSumEnd = currentSumEnd;
maxSumStart = currentSumStart;
}
if (currentSum < 0) {
currentSumStart = currentSumEnd + 1;
currentSum = 0;
}
}
return Arrays.copyOfRange(a, maxSumStart, maxSumEnd+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment