Created
November 7, 2013 18:50
-
-
Save ylegall/7359837 to your computer and use it in GitHub Desktop.
subarray with maximum sum
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
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