-
-
Save bcjordan/ba3db0794d48f705e58b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
int[] getLargestSubArray(int[] array) | |
{ | |
// find the index at which the sum starting from the beginning of the array is the largest | |
int max = array[0]; | |
int maxIndex = 0; | |
int sum = array[0]; | |
for(int x = 1; x < array.length; x++) | |
{ | |
sum += array[x]; | |
if(sum > max) | |
{ | |
max = sum; | |
maxIndex = x; | |
} | |
} | |
// find the index (before the index of the largest sum) at which the sum is the lowest | |
sum = array[0]; | |
int min = array[0]; | |
int minIndex = 0; | |
for(int x = 1; x < maxIndex; x++) | |
{ | |
sum += array[x]; | |
if(sum < min) | |
{ | |
min = sum; | |
minIndex = x; | |
} | |
} | |
return Arrays.copyOfRange(array, minIndex, maxIndex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, doesn't look like this works correctly...
It would be better to re-set max sum to zero if it goes negative, using Kadane's algorithm:
http://en.wikipedia.org/wiki/Maximum_subarray_problem
Also, it doesn't look like the minIndex gets set correctly in certain cases.
Also, with Arrays.copyOfRange(array, from, to), the "to" is exclusive, so it doesn't get included.
http://www.tutorialspoint.com/java/util/arrays_copyofrange_short.htm
With input: {100, -24, -45, 200, -30, 500}
The output (after fixing the copyOfRange issue):
-45 200 -30 500