Last active
August 29, 2015 14:19
-
-
Save StabbyMcDuck/b5f56b8a21b6edd8646d to your computer and use it in GitHub Desktop.
Max subarray
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 class CalcMaxSubArray { | |
double[] maxSubarray(double[] a) { | |
double max_so_far = 0; | |
double max_ending_here = 0; | |
int max_start_index = 0; | |
int startIndex = 0; | |
int max_end_index = -1; | |
for(int i = 0; i < a.length; i++) { | |
if(0 >= max_ending_here +a[i]) { | |
startIndex = i+1; | |
max_ending_here = 0; | |
} | |
else { | |
max_ending_here += a[i]; | |
} | |
if(max_ending_here > max_so_far) { | |
max_so_far = max_ending_here; | |
max_start_index = startIndex; | |
max_end_index = i; | |
} | |
} | |
if(max_start_index <= max_end_index) { | |
return Arrays.copyOfRange(a, max_start_index, max_end_index+1); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment