Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 7, 2013 18:50
Show Gist options
  • Save ylegall/7359837 to your computer and use it in GitHub Desktop.
Save ylegall/7359837 to your computer and use it in GitHub Desktop.
subarray with maximum sum
import std.stdio;
import std.typecons;
auto maxSubArray(T)(T[] array) {
auto start = 0, stop = 0, tmp = 0;
auto maxSum = 0, sum = 0;
foreach (i; 0 .. array.length) {
sum += array[i];
if (sum < 0) {
sum = 0;
tmp = i+1;
}
if (sum >= maxSum) {
maxSum = sum;
start = tmp;
stop = i;
}
}
return tuple(maxSum, start, stop);
}
void main() {
auto array = [1,5,3,-7,9,-13,4,6,0,-3,1];
writeln(array);
auto result = maxSubArray(array);
writeln(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment