RosettaCodeData/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-1.d

31 lines
770 B
D
Raw Permalink Normal View History

2013-06-05 21:47:54 +00:00
import std.stdio;
2015-02-20 00:35:01 -05:00
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc {
2013-06-05 21:47:54 +00:00
int maxSum, thisSum, i, start, end = -1;
2015-02-20 00:35:01 -05:00
foreach (immutable j, immutable x; sequence) {
2013-06-05 21:47:54 +00:00
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];
2015-02-20 00:35:01 -05:00
writeln("Maximal subsequence: ", a1.maxSubseq);
2013-06-05 21:47:54 +00:00
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
2015-02-20 00:35:01 -05:00
writeln("Maximal subsequence: ", a2.maxSubseq);
2013-06-05 21:47:54 +00:00
}