This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,30 @@
import std.stdio;
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow {
int maxSum, thisSum, i, start, end = -1;
foreach (j, x; sequence) {
thisSum += x;
if (thisSum < 0) {
i = j + 1;
thisSum = 0;
} else if (thisSum > maxSum) {
maxSum = thisSum;
start = i;
end = j;
}
}
if (start <= end && start >= 0 && end >= 0)
return sequence[start .. end + 1];
else
return [];
}
void main() {
const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
writeln("Maximal subsequence: ", maxSubseq(a1));
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
writeln("Maximal subsequence: ", maxSubseq(a2));
}