Greatest subsequential sum: Difference between revisions
m
→{{header|EasyLang}}
(→{{header|Quackery}}: improved efficiency) |
|||
(3 intermediate revisions by 2 users not shown) | |||
Line 1,191:
Subsequence: ${seq(indexes.getOptStart(), indexes.getOptBound())}
`)</syntaxhighlight>
{{trans|C}}
proc max_subseq . seq[] start stop maxsum .
maxsum = 0
start = 1
stop = 0
for j to len seq[]
sum += seq[j]
elif sum > maxsum
start = i
stop = j
maxsum = sum
.
.
.
max_subseq a[] a b sum
print "Max sum = " & sum
write a[i] & " "
.
</syntaxhighlight>
{{out}}▼
<pre>▼
</pre>▼
=={{header|EchoLisp}}==
Line 4,018 ⟶ 4,051:
<pre>
<3,5,6,-2,-1,4></pre>
▲=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;▼
int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;▼
[Array:= [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];▼
Size:= 11;▼
Best:= -100000;▼
for Lo:= 0 to Size-1 do▼
for Hi:= Lo to Size-1 do▼
▲ [Sum:= 0;
▲ for I:= Lo to Hi do
Sum:= Sum + Array(I);▼
▲ if Sum > Best then
[Best:= Sum; BLo:= Lo; BHi:= Hi];▼
▲ ];
Text(0, "Sequence = ");▼
for I:= 0 to Size-1 do▼
[IntOut(0, Array(I)); Text(0, " ")];▼
CrLf(0);▼
Text(0, "Greatest = ");▼
▲for I:= BLo to BHi do
[IntOut(0, Array(I)); Text(0, " ")];▼
CrLf(0);▼
Text(0, "Sum = "); IntOut(0, Best); CrLf(0);▼
▲]</syntaxhighlight>
▲{{out}}
▲<pre>
▲Sequence = -1 -2 3 5 6 -2 -1 4 -4 2 -1
▲Greatest = 3 5 6 -2 -1 4
▲Sum = 15
▲</pre>
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="
var best = 0
var start = 0
Line 4,108:
Sub seq: []
Sum: 0
</pre>
=={{header|XPL0}}==
▲<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
▲int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;
▲[Array:= [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
▲Size:= 11;
▲Best:= -100000;
▲for Lo:= 0 to Size-1 do
▲ for Hi:= Lo to Size-1 do
[Sum:= 0;
for I:= Lo to Hi do
▲ Sum:= Sum + Array(I);
if Sum > Best then
▲ [Best:= Sum; BLo:= Lo; BHi:= Hi];
];
▲Text(0, "Sequence = ");
▲for I:= 0 to Size-1 do
▲ [IntOut(0, Array(I)); Text(0, " ")];
▲CrLf(0);
▲Text(0, "Greatest = ");
for I:= BLo to BHi do
▲ [IntOut(0, Array(I)); Text(0, " ")];
▲CrLf(0);
▲Text(0, "Sum = "); IntOut(0, Best); CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
Sequence = -1 -2 3 5 6 -2 -1 4 -4 2 -1
Greatest = 3 5 6 -2 -1 4
Sum = 15
</pre>
|