Greatest subsequential sum: Difference between revisions

m
m (→‎{{header|Sidef}}: Fix link: Perl 6 --> Raku)
 
(33 intermediate revisions by 18 users not shown)
Line 12:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F maxsumseq(sequence)
V (start, end, sum_start) = (-1, -1, -1)
V (maxsum_, sum_) = (0, 0)
Line 29:
print(maxsumseq([-1, 2, -1, 3, -1]))
print(maxsumseq([-1, 1, 2, -5, -6]))
print(maxsumseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]))</langsyntaxhighlight>
 
{{out}}
Line 37:
[1, 2]
[3, 5, 6, -2, -1, 4]
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT first,last)
INT i
 
Put('[)
FOR i=first TO last
DO
IF i>first THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC Process(INT ARRAY a INT size)
INT i,j,beg,end
INT sum,best
 
beg=0 end=-1 best=0
FOR i=0 TO size-1
DO
sum=0
FOR j=i TO size-1
DO
sum==+a(j)
IF sum>best THEN
best=sum
beg=i
end=j
FI
OD
OD
 
Print("Seq=") PrintArray(a,0,size-1)
PrintF("Max sum=%i %ESubseq=",best)
PrintArray(a,beg,end) PutE()
RETURN
 
PROC Main()
INT ARRAY
a(11)=[1 2 3 4 5 65528 65527 65516 40 25 65531],
b(11)=[65535 65534 3 5 6 65534 65535 4 65532 2 65535],
c(5)=[65535 65534 65533 65532 65531],
d(0)=[]
Process(a,11)
Process(b,11)
Process(c,5)
Process(d,0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Greatest_subsequential_sum.png Screenshot from Atari 8-bit computer]
<pre>
Seq=[1 2 3 4 5 -8 -9 -20 40 25 -5]
Max sum=65
Subseq=[40 25]
 
Seq=[-1 -2 3 5 6 -2 -1 4 -4 2 -1]
Max sum=15
Subseq=[3 5 6 -2 -1 4]
 
Seq=[-1 -2 -3 -4 -5]
Max sum=0
Subseq=[]
 
Seq=[]
Max sum=0
Subseq=[]
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Max_Subarray is
Line 77 ⟶ 146:
when Empty_Error =>
Put_Line("Array being analyzed has no elements.");
end Max_Subarray;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">gsss(list l, integer &start, &end, &maxsum)
{
integer e, f, i, sum;
Line 112 ⟶ 181:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre>Max sum 15
Line 122 ⟶ 191:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">main:
(
[]INT a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
Line 150 ⟶ 219:
OD
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 159 ⟶ 228:
{{Trans|Haskell}}
Linear derivation of both sum and list, in a single fold:
<langsyntaxhighlight lang="applescript">-- maxSubseq :: [Int] -> [Int] -> (Int, [Int])
on maxSubseq(xs)
script go
Line 247 ⟶ 316:
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple</langsyntaxhighlight>
{{Out}}
<pre>{15, {3, 5, 6, -2, -1, 4}}</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">subarraySum: function [arr][
curr: 0
mx: 0
fst: size arr
lst: 0
currFst: 0
 
loop.with: 'i arr [e][
curr: curr + e
if e > curr [
curr: e
currFst: i
]
if curr > mx [
mx: curr
fst: currFst
lst: i
]
]
if? lst > fst -> return @[mx, slice arr fst lst]
else -> return [0, []]
]
 
sequences: @[
@[1, 2, 3, 4, 5, neg 8, neg 9, neg 20, 40, 25, neg 5]
@[neg 1, neg 2, 3, 5, 6, neg 2, neg 1, 4, neg 4, 2, neg 1]
@[neg 1, neg 2, neg 3, neg 4, neg 5]
@[]
]
 
loop sequences 'seq [
print [pad "sequence:" 15 seq]
processed: subarraySum seq
print [pad "max sum:" 15 first processed]
print [pad "subsequence:" 15 last processed "\n"]
]</syntaxhighlight>
 
{{out}}
 
<pre> sequence: [1 2 3 4 5 -8 -9 -20 40 25 -5]
max sum: 65
subsequence: [40 25]
sequence: [-1 -2 3 5 6 -2 -1 4 -4 2 -1]
max sum: 15
subsequence: [3 5 6 -2 -1 4]
sequence: [-1 -2 -3 -4 -5]
max sum: 0
subsequence: []
sequence: []
max sum: 0
subsequence: [] </pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(*
** This one is
Line 324 ⟶ 450:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 333 ⟶ 459:
=={{header|AutoHotkey}}==
classic algorithm:
<langsyntaxhighlight AutoHotkeylang="autohotkey">seq = -1,-2,3,5,6,-2,-1,4,-4,2,-1
max := sum := start := 0
Loop Parse, seq, `,
Line 343 ⟶ 469:
Loop Parse, seq, `,
s .= A_Index > a && A_Index <= b ? A_LoopField "," : ""
MsgBox % "Max = " max "`n[" SubStr(s,1,-1) "]"</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Local $iArray[11] = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
GREAT_SUB($iArray)
Line 383 ⟶ 509:
ConsoleWrite("]" & @CRLF & "!>SUM of subsequence: " & $iSUM & @CRLF)
EndFunc ;==>GREAT_SUB
</syntaxhighlight>
</lang>
 
{{out}}
Line 398 ⟶ 524:
=={{header|AWK}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang="awk"># Finds the subsequence of ary[1] to ary[len] with the greatest sum.
# Sets subseq[1] to subseq[n] and returns n. Also sets subseq["sum"].
# An empty subsequence has sum 0.
Line 425 ⟶ 551:
subseq["sum"] = b
return bn
}</langsyntaxhighlight>
 
Demonstration: <langsyntaxhighlight lang="awk"># Joins the elements ary[1] to ary[len] in a string.
function join(ary, len, i, s) {
s = "["
Line 452 ⟶ 578:
try("0 1 2 -3 3 -1 0 -4 0 -1 -4 2")
try("-1 -2 3 5 6 -2 -1 4 -4 2 -1")
}</langsyntaxhighlight>
 
{{out}}
Line 463 ⟶ 589:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM A%(11) : A%() = 0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2
PRINT FNshowarray(A%()) " -> " FNmaxsubsequence(A%())
DIM B%(10) : B%() = -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1
Line 498 ⟶ 624:
a$ += STR$(a%(i%)) + ", "
NEXT
= LEFT$(LEFT$(a$)) + "]"</langsyntaxhighlight>
{{out}}
<pre>
Line 510 ⟶ 636:
This program iterates over all subsequences by forced backtracking, caused by the failing node <code>~</code> at the end of the middle part of the pattern. The combination of flags <code>[%</code> on an expression creates a pattern that succeeds if and only if the expression is successfully evaluated. <code>sjt</code> is an extra argument to any function that is part of a pattern and it contains the current subexpression candidate. Inside the pattern the function <code>sum</code> sums over all elements in <code>sjt</code>. The currently longest maximal subsequence is kept in <code>seq</code>.
 
<langsyntaxhighlight lang="bracmat">
( 0:?max
& :?seq
Line 533 ⟶ 659:
| !seq
)
</syntaxhighlight>
</lang>
 
<pre>3 5 6 -2 -1 4</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include "stdio.h"
 
typedef struct Range {
Line 585 ⟶ 711:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Max sum = 15
Line 592 ⟶ 718:
=={{header|C sharp|C#}}==
'''The challange'''
<langsyntaxhighlight lang="csharp">using System;
 
namespace Tests_With_Framework_4
Line 624 ⟶ 750:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <utility> // for std::pair
#include <iterator> // for std::iterator_traits
#include <iostream> // for std::cout
Line 715 ⟶ 841:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
{{trans|Haskell}}
Naive algorithm:
<langsyntaxhighlight lang="clojure">(defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails
(mapcat #(reductions conj [] %)) ; inits
(apply max-key #(reduce + %)))) ; max sum</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="clojure">user> (max-subseq-sum [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
[3 5 6 -2 -1 4]</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
max_sum_seq = (sequence) ->
# This runs in linear time.
Line 749 ⟶ 875:
console.log max_sum_seq [-1]
console.log max_sum_seq [4, -10, 3]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 757 ⟶ 883:
Returns the maximum subsequence sum, the subsequence with the maximum sum, and start and end indices for the subsequence within the original sequence. Based on the implementation at [http://wordaligned.org/articles/the-maximum-subsequence-problem Word Aligned]. Leading zeroes aren't trimmed from the subsequence.
 
<langsyntaxhighlight lang="lisp">(defun max-subseq (list)
(let ((best-sum 0) (current-sum 0) (end 0))
;; determine the best sum, and the end of the max subsequence
Line 775 ⟶ 901:
(sum sum (- sum (first sublist))))
((or (endp sublist) (eql sum best-sum))
(values best-sum sublist start (1+ end)))))))</langsyntaxhighlight>
 
For example,
Line 795 ⟶ 921:
{{trans|PicoLisp}}
 
<langsyntaxhighlight lang="lisp">(defun max-subseq (seq)
(loop for subsequence in (mapcon (lambda (x) (maplist #'reverse (reverse x))) seq)
for sum = (reduce #'+ subsequence :initial-value 0)
Line 801 ⟶ 927:
maximizing sum into max
if (= sum max) do (setf max-subsequence subsequence)
finally (return max-subsequence))))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
Works with BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE OvctGreatestSubsequentialSum;
IMPORT StdLog, Strings, Args;
Line 851 ⟶ 977:
 
END OvctGreatestSubsequentialSum.
</syntaxhighlight>
</lang>
Execute: <br/>
<pre>
Line 861 ⟶ 987:
[ 3, 5, 6, -2, -1, 4]= 15
[]= 0
</pre>
 
=={{header|Crystal}}==
===Brute Force:===
{{trans|Ruby}}
Answer is stored in "slice". It is very slow O(n**3)
<syntaxhighlight lang="ruby">def subarray_sum(arr)
max, slice = 0, [] of Int32
arr.each_index do |i|
(i...arr.size).each do |j|
sum = arr[i..j].sum
max, slice = sum, arr[i..j] if sum > max
end
end
[max, slice]
end</syntaxhighlight>
 
===Linear Time Version:===
{{trans|Ruby}}
A better answer would run in O(n) instead of O(n**2) using numerical properties to remove the need for the inner loop.
 
<syntaxhighlight lang="ruby"># the trick is that at any point
# in the iteration if starting a new chain is
# better than your current score with this element
# added to it, then do so.
# the interesting part is proving the math behind it
def subarray_sum(arr)
curr = max = 0
first, last, curr_first = arr.size, 0, 0
arr.each_with_index do |e, i|
curr += e
e > curr && (curr = e; curr_first = i)
curr > max && (max = curr; first = curr_first; last = i)
end
return max, arr[first..last]
end</syntaxhighlight>
 
'''Test:'''
<syntaxhighlight lang="ruby">[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
[-1, -2, -3, -4, -5],
[] of Int32
].each do |input|
puts "\nInput seq: #{input}"
puts " Max sum: %d\n Subseq: %s" % subarray_sum(input)
end</syntaxhighlight>
{{out}}
<pre>
Input seq: [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5]
Max sum: 65
Subseq: [40, 25]
 
Input seq: [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
Max sum: 15
Subseq: [3, 5, 6, -2, -1, 4]
 
Input seq: [-1, -2, -3, -4, -5]
Max sum: 0
Subseq: []
 
Input seq: []
Max sum: 0
Subseq: []
</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio;
 
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc {
Line 894 ⟶ 1,083:
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
writeln("Maximal subsequence: ", a2.maxSubseq);
}</langsyntaxhighlight>
{{out}}
<pre>Maximal subsequence: [3, 5, 6, -2, -1, 4]
Line 905 ⟶ 1,094:
and max can't be used as the maximumBy functions
(for the concatMap a map.join is enough).
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
mixin template InitsTails(T) {
Line 938 ⟶ 1,127:
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1].maxSubseq.writeln;
[-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1].maxSubseq.writeln;
}</langsyntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Greatest_subsequential_sum#Pascal Pascal].
 
=={{header|E}}==
Line 947 ⟶ 1,138:
<code>maxSubseq</code> returns both the maximum sum found, and the interval of indexes which produces it.
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
 
def maxSubseq(seq) {
Line 990 ⟶ 1,181:
return ["value" => maxValue,
"indexes" => maxInterval]
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">def seq := [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
def [=> value, => indexes] := maxSubseq(seq)
println(`$\
Line 999 ⟶ 1,190:
Indexes: ${indexes.getOptStart()}..${indexes.getOptBound().previous()}
Subsequence: ${seq(indexes.getOptStart(), indexes.getOptBound())}
`)</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
proc max_subseq . seq[] start stop maxsum .
maxsum = 0
i = 1
start = 1
stop = 0
for j to len seq[]
sum += seq[j]
if sum < 0
i = j + 1
sum = 0
elif sum > maxsum
start = i
stop = j
maxsum = sum
.
.
.
a[] = [ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ]
max_subseq a[] a b sum
print "Max sum = " & sum
for i = a to b
write a[i] & " "
.
</syntaxhighlight>
{{out}}
<pre>
Max sum = 15
3 5 6 -2 -1 4
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'struct)
(struct result (score starter))
Line 1,038 ⟶ 1,262:
(max-seq L)
→ (15 (3 5 6 -2 -1 4))
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
===Linear Time Version:===
<syntaxhighlight lang="elixir">defmodule Greatest do
def subseq_sum(list) do
list_i = Enum.with_index(list)
acc = {0, 0, length(list), 0, 0}
{_,max,first,last,_} = Enum.reduce(list_i, acc, fn {elm,i},{curr,max,first,last,curr_first} ->
if curr < 0 do
if elm > max, do: {elm, elm, i, i, curr_first},
else: {elm, max, first, last, curr_first}
else
cur2 = curr + elm
if cur2 > max, do: {cur2, cur2, curr_first, i, curr_first},
else: {cur2, max, first, last, curr_first}
end
end)
{max, Enum.slice(list, first..last)}
end
end</syntaxhighlight>
Output is the same above.
 
===Brute Force:===
<langsyntaxhighlight lang="elixir">defmodule Greatest do
def subseq_sum(list) do
limit = length(list) - 1
Line 1,053 ⟶ 1,297:
end)
end
end</langsyntaxhighlight>
 
'''Test:'''
<langsyntaxhighlight lang="elixir">data = [ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
[-1, -2, -3, -4, -5],
Line 1,064 ⟶ 1,308:
{max, subseq} = Greatest.subseq_sum(input)
IO.puts " Max sum: #{max}\n Subseq: #{inspect subseq}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,084 ⟶ 1,328:
Subseq: []
</pre>
 
===Linear Time Version:===
<lang elixir>defmodule Greatest do
def subseq_sum(list) do
list_i = Enum.with_index(list)
acc = {0, 0, length(list), 0, 0}
{_,max,first,last,_} = Enum.reduce(list_i, acc, fn {elm,i},{curr,max,first,last,curr_first} ->
if curr < 0 do
if elm > max, do: {elm, elm, i, i, curr_first},
else: {elm, max, first, last, curr_first}
else
cur2 = curr + elm
if cur2 > max, do: {cur2, cur2, curr_first, i, curr_first},
else: {cur2, max, first, last, curr_first}
end
end)
{max, Enum.slice(list, first..last)}
end
end</lang>
Output is the same above.
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM MAX_SUM
 
Line 1,174 ⟶ 1,398:
!$ERASE P%
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
Line 1,180 ⟶ 1,404:
The following recursive system seems to have a run time of O(n), but it needs some copying, so the run time is really O(n^2).
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function %maxsubs (v,n) ...
$if n==1 then
Line 1,204 ⟶ 1,428:
>maxsubs([-1, -2, -3, -4, -5])
Empty matrix of size 1x0
</syntaxhighlight>
</lang>
 
Here is a brute force method producing and testing all sums. The runtime is O(n^3).
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function maxsubsbrute (v) ...
$ n=cols(v);
Line 1,228 ⟶ 1,452:
>maxsubsbrute([-1, -2, -3, -4, -5])
Empty matrix of size 1x0
</syntaxhighlight>
</lang>
 
To see, if everything works, the following tests on 10 million random sequences.
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function test ...
$ loop 1 to 10000000
Line 1,241 ⟶ 1,465:
$ endfunction
>test
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function maxSubseq(sequence s)
integer sum, maxsum, first, last
maxsum = 0
Line 1,265 ⟶ 1,489:
? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1})
? maxSubseq({})
? maxSubseq({-1, -5, -3})</langsyntaxhighlight>
 
{{out}}
Line 1,273 ⟶ 1,497:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let maxsubseq s =
let (_, _, maxsum, maxseq) =
List.fold (fun (sum, seq, maxsum, maxseq) x ->
Line 1,283 ⟶ 1,507:
List.rev maxseq
 
printfn "%A" (maxsubseq [-1 ; -2 ; 3 ; 5 ; 6 ; -2 ; -1 ; 4; -4 ; 2 ; -1])</langsyntaxhighlight>
{{out}}
<pre>[3; 5; 6; -2; -1; 4]</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel locals math math.order sequences ;
 
:: max-with-index ( elt0 ind0 elt1 ind1 -- elt ind )
Line 1,296 ⟶ 1,520:
: max-subseq ( seq -- subseq )
dup 0 [ + 0 max ] accumulate swap suffix last-of-max head
dup 0 [ + ] accumulate swap suffix [ neg ] map last-of-max tail ;</langsyntaxhighlight>
<langsyntaxhighlight lang="factor">( scratchpad ) { -1 -2 3 5 6 -2 -1 4 -4 2 -1 } max-subseq dup sum swap . .
{ 3 5 6 -2 -1 4 }
15</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">2variable best
variable best-sum
 
Line 1,324 ⟶ 1,548:
 
create test -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1 ,
create test2 -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , 99 ,</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="forth">test 11 max-sub .array [3 5 6 -2 -1 4 ] = 15 ok
test2 11 max-sub .array [3 5 6 -2 -1 4 -4 2 99 ] = 112 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program MaxSubSeq
implicit none
 
Line 1,346 ⟶ 1,570:
print *, a(m(1):m(2))
 
end program MaxSubSeq</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As Integer seq(10) = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1}
Line 1,384 ⟶ 1,608:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,394 ⟶ 1,618:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,429 ⟶ 1,653:
fmt.Println("Sum: ", sum, "\n")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,451 ⟶ 1,675:
=={{header|Haskell}}==
Naive approach which tests all possible subsequences, as in a few of the other examples. For fun, this is in point-free style and doesn't use loops:
<langsyntaxhighlight lang="haskell">import Data.List (inits, tails, maximumBy)
import Data.Ord (comparing)
 
Line 1,460 ⟶ 1,684:
maxsubseq = maximumBy (comparing sum) . subseqs
 
main = print $ maxsubseq [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]</langsyntaxhighlight>
Secondly, the linear time constant space approach:
<langsyntaxhighlight lang="haskell">maxSubseq :: [Int] -> (Int, [Int])
maxSubseq =
let go x ((h1, h2), sofar) =
Line 1,469 ⟶ 1,693:
 
main :: IO ()
main = print $ maxSubseq [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]</langsyntaxhighlight>
{{Out}}
<pre>(15,[3,5,6,-2,-1,4])</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
L1 := [-1,-2,3,5,6,-2,-1,4,-4,2,-1] # sample list
L := [-1,1,2,3,4,-11]|||L1 # prepend a local maximum into the mix
Line 1,495 ⟶ 1,719:
}
return L[(\maxglobalI)[1]:maxglobalI[2]] | [] # return sub-sequence or empty list
end</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Subseq.bas"
110 RANDOMIZE
120 NUMERIC A(1 TO 15)
Line 1,519 ⟶ 1,743:
290 PRINT A(I);
300 NEXT
310 PRINT :PRINT "Sum:";MAXSUM</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">maxss=: monad define
AS =. 0,; <:/~@i.&.> #\y
MX =. (= >./) AS +/ . * y
y #~ {. MX#AS
)</langsyntaxhighlight>
 
<tt>y</tt> is the input vector, an integer list.<br>
Line 1,536 ⟶ 1,760:
If zero is the maximal sum the empty array is always returned, although sub-sequences of positive length (comprised of zeros) might be more interesting.<br>
Example use:
<langsyntaxhighlight lang="j"> maxss _1 _2 3 5 6 _2 _1 4 _4 2 _1
3 5 6 _2 _1 4</langsyntaxhighlight>
 
Note: if we just want the sum of the maximum subsequence,
and are not concerned with the subsequence itself, we can use:
 
<langsyntaxhighlight lang="j">maxs=: [:>./(0>.+)/\.</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="j"> maxs _1 _2 3 5 6 _2 _1 4 _4 2 _1
15</langsyntaxhighlight>
 
This suggests a variant:
<langsyntaxhighlight lang="j">maxSS=:monad define
sums=: (0>.+)/\. y
start=: sums i. max=: >./ sums
max (] {.~ #@] |&>: (= +/\) i. 1:) y}.~start
)</langsyntaxhighlight>
or
<langsyntaxhighlight lang="j">maxSS2=:monad define
start=. (i. >./) (0>.+)/\. y
({.~ # |&>: [: (i.>./@,&0) +/\) y}.~start
)</langsyntaxhighlight>
 
These variants are considerably faster than the first implementation, on long sequences.
Line 1,567 ⟶ 1,791:
 
The method <tt>nextChoices</tt> was modified from an [http://www.cs.rit.edu/~vcss233/Labs/newlab02/index.html RIT CS lab].
<langsyntaxhighlight lang="java">import java.util.Scanner;
import java.util.ArrayList;
 
Line 1,623 ⟶ 1,847:
return false;
}
}</langsyntaxhighlight>
 
This one runs in linear time, and isn't generalized.
<langsyntaxhighlight lang="java">private static int BiggestSubsum(int[] t) {
int sum = 0;
int maxsum = 0;
Line 1,637 ⟶ 1,861:
}
return maxsum;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===Imperative===
Simple brute force approach.
<langsyntaxhighlight lang="javascript">function MaximumSubsequence(population) {
var maxValue = 0;
var subsequence = [];
Line 1,666 ⟶ 1,890:
}
return result;
}</langsyntaxhighlight>
 
===Functional===
{{Trans|Haskell}}
Linear approach, deriving both list and sum in a single accumulating fold.
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// maxSubseq :: [Int] -> (Int, [Int])
Line 1,729 ⟶ 1,953:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[3,5,6,-2,-1,4] -> 15</pre>
Line 1,737 ⟶ 1,961:
 
This is the same linear-time algorithm as used in the [[#Ruby]] subsection on this page.
<langsyntaxhighlight lang="jq">def subarray_sum:
. as $arr
| reduce range(0; length) as $i
Line 1,747 ⟶ 1,971:
else .
end)
| [ .max, $arr[ .first : (1 + .last)] ];</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">[1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5] | subarray_sum</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f Greatest_subsequential_sum.jq
[65,[40,25]]</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Greatest Subsequential Sum, in Jsish */
function sumValues(arr) {
var result = 0;
Line 1,792 ⟶ 2,016:
greatestSubsequentialSum(gss) ==> [ 15, [ 3, 5, 6, -2, -1, 4 ] ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,802 ⟶ 2,026:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function gss(arr::Vector{<:Number})
smax = hmax = tmax = 0
for head in eachindex(arr), tail in head:length(arr)
Line 1,818 ⟶ 2,042:
s = sum(subseq)
 
println("Greatest subsequential sum of $arr:\n → $subseq with sum $s")</langsyntaxhighlight>
 
{{out}}
Line 1,825 ⟶ 2,049:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun gss(seq: IntArray): Triple<Int, Int, Int> {
Line 1,858 ⟶ 2,082:
else
println("Maximum subsequence is the empty sequence which has a sum of 0")
}</langsyntaxhighlight>
 
{{out}}
Line 1,868 ⟶ 2,092:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'Greatest_subsequential_sum
 
Line 1,921 ⟶ 2,145:
print
end sub
</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end
function maxsub(ary, idx)
local idx = idx or 1
Line 1,937 ⟶ 2,161:
for i = idx, last do ret[#ret+1] = ary[i] end
return ret
end</langsyntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,
incr($2),shift(shift(shift($@))))')')
Line 1,955 ⟶ 2,179:
`define(`maxsum',sum)`'define(`xmax',x)`'define(`ymax',y)')')')
divert
for(`x',xmax,ymax,`get(`a',x) ')</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
===Method 1===
First we define 2 functions, one that gives all possibles subsequences (as a list of lists of indices) for a particular length. Then another extract those indices adds them up and looks for the largest sum.
<langsyntaxhighlight Mathematicalang="mathematica">Sequences[m_]:=Prepend[Flatten[Table[Partition[Range[m],n,1],{n,m}],1],{}]
MaximumSubsequence[x_List]:=Module[{sums},
sums={x[[#]],Total[x[[#]]]}&/@Sequences[Length[x]];
First[First[sums[[Ordering[sums,-1,#1[[2]]<#2[[2]]&]]]]]
]</langsyntaxhighlight>
 
===Method 2===
<langsyntaxhighlight Mathematicalang="mathematica">MaximumSubsequence[x_List]:=Last@SortBy[Flatten[Table[x[[a;;b]], {b,Length[x]}, {a,b}],1],Total]</langsyntaxhighlight>
 
===Examples===
<langsyntaxhighlight Mathematicalang="mathematica">MaximumSubsequence[{-1,-2,3,5,6,-2,-1,4,-4,2,-1}]
MaximumSubsequence[{2,4,5}]
MaximumSubsequence[{2,-4,3}]
MaximumSubsequence[{4}]
MaximumSubsequence[{}]</langsyntaxhighlight>
gives back:
<pre>{3,5,6,-2,-1,4}
Line 1,984 ⟶ 2,208:
=={{header|Mathprog}}==
see [[wp:Special_ordered_set]]. Lmin specifies the minimum length of the required subsequence, and Lmax the maximum.
<syntaxhighlight lang="text">
/*Special ordered set of type N
 
Line 2,021 ⟶ 2,245:
 
end;
</syntaxhighlight>
</lang>
 
produces:
 
<syntaxhighlight lang="text">
GLPSOL: GLPK LP/MIP Solver, v4.47
Parameter(s) specified in the command line:
Line 2,065 ⟶ 2,289:
Model has been successfully processed
 
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function [S,GS]=gss(a)
% Greatest subsequential sum
a =[0;a(:);0]';
Line 2,082 ⟶ 2,306:
end;
GS = a(ix1(K)+1:ix2(K));
</syntaxhighlight>
</lang>
 
Usage:
Line 2,093 ⟶ 2,317:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* REXX ***************************************************************
* 10.08.2012 Walter Pachl Pascal algorithm -> Rexx -> NetRexx
**********************************************************************/
Line 2,124 ⟶ 2,348:
Say ol
Say 'Sum:' maxSum
End</langsyntaxhighlight>
Output: the same as for Rexx
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc maxsum(s: openArray[int]): int =
var maxendinghere = 0
for x in s:
Line 2,134 ⟶ 2,358:
result = max(result, maxendinghere)
 
echo maxsum(@[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])</langsyntaxhighlight>
 
{{out}}
<pre>15</pre>
 
=={{header|Oberon-2}}==
Works with oo2c Version 2
<langsyntaxhighlight lang="oberon2">
MODULE GreatestSubsequentialSum;
IMPORT
Line 2,225 ⟶ 2,452:
END GreatestSubsequentialSum.
 
</syntaxhighlight>
</lang>
Execute:<br/>
<pre>
Line 2,238 ⟶ 2,465:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let maxsubseq =
let rec loop sum seq maxsum maxseq = function
| [] -> maxsum, List.rev maxseq
Line 2,254 ⟶ 2,481:
 
let _ =
maxsubseq [-1 ; -2 ; 3 ; 5 ; 6 ; -2 ; -1 ; 4; -4 ; 2 ; -1]</langsyntaxhighlight>
 
This returns a pair of the maximum sum and (one of) the maximum subsequence(s).
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {MaxSubSeq Xs}
 
Line 2,282 ⟶ 2,509:
end
in
{Show {MaxSubSeq [~1 ~2 3 5 6 ~2 ~1 4 ~4 2 1]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Naive quadratic solution (with end-trimming).
<langsyntaxhighlight lang="parigp">grsub(v)={
my(mn=1,mx=#v,r=0,at,c);
if(vecmax(v)<=0,return([1,0]));
Line 2,299 ⟶ 2,526:
);
at
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program GreatestSubsequentialSum(output);
 
var
Line 2,341 ⟶ 2,568:
writeln ('Sum:');
writeln (maxSum);
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./GreatestSubsequentialSum
Line 2,354 ⟶ 2,581:
=={{header|Perl}}==
O(n) running-sum method:
<langsyntaxhighlight lang="perl">use strict;
 
sub max_sub(\@) {
Line 2,374 ⟶ 2,601:
 
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,384 ⟶ 2,611:
 
Naive and potentionally very slow method:
<langsyntaxhighlight lang="perl">use strict;
 
my @a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
Line 2,402 ⟶ 2,629:
}
 
print "@maxsubarray\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function maxSubseq(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer this, maxsum = 0, first = 1, last = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">maxSubseq</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">maxsum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">first</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
this = 0
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for j=i to length(s) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">sumsij</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
this += s[j]
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if this>maxsum then
<span style="color: #000000;">sumsij</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
{maxsum,first,last} = {this,i,j}
<span style="color: #008080;">if</span> <span style="color: #000000;">sumsij</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxsum</span> <span style="color: #008080;">then</span>
end if
<span style="color: #0000FF;">{</span><span style="color: #000000;">maxsum</span><span style="color: #0000FF;">,</span><span style="color: #000000;">first</span><span style="color: #0000FF;">,</span><span style="color: #000000;">last</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">sumsij</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">}</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return s[first..last]
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">first</span><span style="color: #0000FF;">..</span><span style="color: #000000;">last</span><span style="color: #0000FF;">]</span>
? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1})
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
? maxSubseq({})
<span style="color: #0000FF;">?</span> <span style="color: #000000;">maxSubseq</span><span style="color: #0000FF;">({-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
? maxSubseq({-1, -5, -3})</lang>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">maxSubseq</span><span style="color: #0000FF;">({})</span>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">maxSubseq</span><span style="color: #0000FF;">({-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,431 ⟶ 2,661:
=={{header|PHP}}==
 
<syntaxhighlight lang="php">
<lang PHP>
<?php
Line 2,470 ⟶ 2,700:
print_array(max_sum_seq(array(4, -10, 3)));
?>
</syntaxhighlight>
</lang>
{{out}} in browser:
<syntaxhighlight lang="text">
0 15 3 -9 12
(empty)
4
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
Here are two versions: one iterative and one using constraint modelling (constraint programming solver).
 
===Iterative===
First build a map with all the combinations then pick the one with greatest sum.
<syntaxhighlight lang="picat">greatest_subsequential_sum_it([]) = [] => true.
greatest_subsequential_sum_it(A) = Seq =>
P = allcomb(A),
Total = max([Tot : Tot=_T in P]),
Seq1 = [],
if Total > 0 then
[B,E] = P.get(Total),
Seq1 := [A[I] : I in B..E]
else
Seq1 := []
end,
Seq = Seq1.
 
allcomb(A) = Comb =>
Len = A.length,
Comb = new_map([(sum([A[I]:I in B..E])=([B,E])) : B in 1..Len, E in B..Len]).</syntaxhighlight>
 
===Constraint modelling===
(This was inspired by a MiniZinc model created by Claudio Cesar de Sá.)
<syntaxhighlight lang="picat">greatest_subsequential_sum_cp([]) = [] => true.
greatest_subsequential_sum_cp(A) = Seq =>
N = A.length,
 
% decision variables: start and end indices
Begin :: 1..N,
End :: 1..N,
 
% 1 if the number is in the selected sequence, 0 if not.
X = new_list(N),
X :: 0..1,
 
% Get the total sum (to be maximized)
TotalSum #= sum([X[I]*A[I] : I in 1..N]),
SizeWindow #= sum(X),
 
% Calculate the windows of the greatest subsequential sum
End #>= Begin,
End - Begin #= SizeWindow -1,
foreach(I in 1..N)
(Begin #=< I #/\ End #>= I) #<=> X[I] #= 1
end,
Vars = X ++ [Begin,End],
solve($[inout,updown,max(TotalSum)], Vars),
 
if TotalSum > 0 then
Seq = [A[I] : I in Begin..End]
else
Seq = []
end.</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">import cp.
 
go =>
LL = [[-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1],
[-1,-2, 3],
[-1,-2],
[0],
[],
[144, 5, -8, 7, 15],
[144, -145, -8, 7, 15],
[-144, 5, -8, 7, 15]
],
 
println("Iterative version:"),
foreach(L in LL)
printf("%w: ", L),
G = greatest_subsequential_sum_it(L),
println([gss=G, sum=sum(G)])
end,
nl,
println("Constraint model"),
foreach(L in LL)
printf("%w: ", L),
G = greatest_subsequential_sum_cp(L),
println([gss=G, sum=sum(G)])
end,
 
nl.</syntaxhighlight>
 
{{out}}
<pre>Iterative version:
[-1,-2,3,5,6,-2,-1,4,-4,2,-1]: [gss = [3,5,6,-2,-1,4],sum = 15]
[-1,-2,3]: [gss = [3],sum = 3]
[-1,-2]: [gss = [],sum = 0]
[0]: [gss = [],sum = 0]
[]: [gss = [],sum = 0]
[144,5,-8,7,15]: [gss = [144,5,-8,7,15],sum = 163]
[144,-145,-8,7,15]: [gss = [144],sum = 144]
[-144,5,-8,7,15]: [gss = [7,15],sum = 22]
 
Constraint model
[-1,-2,3,5,6,-2,-1,4,-4,2,-1]: [gss = [3,5,6,-2,-1,4],sum = 15]
[-1,-2,3]: [gss = [3],sum = 3]
[-1,-2]: [gss = [],sum = 0]
[0]: [gss = [],sum = 0]
[]: [gss = [],sum = 0]
[144,5,-8,7,15]: [gss = [144,5,-8,7,15],sum = 163]
[144,-145,-8,7,15]: [gss = [144],sum = 144]
[-144,5,-8,7,15]: [gss = [7,15],sum = 22]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(maxi '((L) (apply + L))
(mapcon '((L) (maplist reverse (reverse L)))
(-1 -2 3 5 6 -2 -1 4 -4 2 -1) ) )</langsyntaxhighlight>
{{out}}
<pre>-> (3 5 6 -2 -1 4)</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref;
ss: Proc Options(Main);
/* REXX ***************************************************************
Line 2,526 ⟶ 2,864:
Put Edit('Sum:',maxSum)(Skip,a,f(5));
End;
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,537 ⟶ 2,875:
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">gss = (lst) :
# Find discrete integral
integral = (0)
Line 2,566 ⟶ 2,904:
gss((-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1))
gss((-1, -2, -3, -4, -5))
gss((7,-6, -8, 5, -2, -6, 7, 4, 8, -9, -3, 2, 6, -4, -6))</langsyntaxhighlight>
 
<pre>
Line 2,578 ⟶ 2,916:
CHR is a programming language created by '''Professor Thom Frühwirth'''.<br>
Works with SWI-Prolog and module CHR written by '''Tom Schrijvers''' and '''Jan Wielemaker'''.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(chr)).
 
:- chr_constraint
Line 2,632 ⟶ 2,970:
 
memoseq(DC, LC, TTC), gss(_D, _L, TT) <=> TTC > TT |
gss(DC, LC, TTC).</langsyntaxhighlight>
{{out}}
<pre> ?- greatest_subsequence.
Line 2,643 ⟶ 2,981:
===Brute Force===
Works with [https://rosettacode.org/wiki/GNU_Prolog GNU Prolog].
<langsyntaxhighlight Prologlang="prolog">subseq(Sub, Seq) :- suffix(X, Seq), prefix(Sub, X).
 
maxsubseq(List, Sub, Sum) :-
Line 2,650 ⟶ 2,988:
max_list(Sums, Sum),
nth(N, Sums, Sum),
nth(N, Subs, Sub).</langsyntaxhighlight>
{{out}}
<pre>| ?- maxsubseq([-1,-2,3,5,6,-2,-1,4,-4,2,-1], Sub, Sum).
Line 2,661 ⟶ 2,999:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define s$, a, b, p1, p2, sum, max, dm=(?EndOfMyData-?MyData)
Dim Seq.i(dm/SizeOf(Integer))
Line 2,695 ⟶ 3,033:
Data.i -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1
EndOfMyData:
EndDataSection</langsyntaxhighlight>
 
=={{header|Python}}==
===Imperative===
Naive, inefficient but really simple solution which tests all possible subsequences, as in a few of the other examples:
<langsyntaxhighlight lang="python">def maxsubseq(seq):
return max((seq[begin:end] for begin in xrange(len(seq)+1)
for end in xrange(begin, len(seq)+1)),
key=sum)</langsyntaxhighlight>
 
Classic linear-time constant-space solution based on algorithm from "Programming Pearls" book.
<langsyntaxhighlight lang="python">def maxsum(sequence):
"""Return maximum sum."""
maxsofar, maxendinghere = 0, 0
Line 2,713 ⟶ 3,051:
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar</langsyntaxhighlight>
Adapt the above-mentioned solution to return maximizing subsequence. See http://www.java-tips.org/java-se-tips/java.lang/finding-maximum-contiguous-subsequence-sum-using-divide-and-conquer-app.html
<langsyntaxhighlight lang="python">def maxsumseq(sequence):
start, end, sum_start = -1, -1, -1
maxsum_, sum_ = 0, 0
Line 2,728 ⟶ 3,066:
assert maxsum_ == maxsum(sequence)
assert maxsum_ == sum(sequence[start + 1:end + 1])
return sequence[start + 1:end + 1]</langsyntaxhighlight>
Modify ``maxsumseq()`` to allow any iterable not just sequences.
<langsyntaxhighlight lang="python">def maxsumit(iterable):
maxseq = seq = []
start, end, sum_start = -1, -1, -1
Line 2,743 ⟶ 3,081:
sum_start = i
assert maxsum_ == sum(maxseq[:end - start])
return maxseq[:end - start]</langsyntaxhighlight>
Elementary tests:
<langsyntaxhighlight lang="python">f = maxsumit
assert f([]) == []
assert f([-1]) == []
Line 2,761 ⟶ 3,099:
assert f([-1, 2, -1, 3]) == [2, -1, 3]
assert f([-1, 2, -1, 3, -1]) == [2, -1, 3]
assert f([-1, 1, 2, -5, -6]) == [1,2]</langsyntaxhighlight>
 
===Functional===
Line 2,767 ⟶ 3,105:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Greatest subsequential sum'''
 
from functools import (reduce)
Line 2,787 ⟶ 3,125:
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
)
)</langsyntaxhighlight>
{{Out}}
<pre>(15, [3, 5, 6, -2, -1, 4])</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ stack ] is maxseq ( --> s )
[ stack ] is maxsum ( --> s )
 
[ [] maxseq put
0 maxsum put
dup dup size times
[ [] 0 rot
witheach
[ rot over join
unrot +
dup maxsum share >
if
[ dup maxsum replace
over maxseq replace ] ]
2drop behead drop dup ]
2drop
maxsum take
maxseq take ] is maxsubseqsum ( [ --> n [ )
 
 
' [ [ 1 2 3 4 5 -8 -9 -20 40 25 -5 ]
[ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ]
[ -1 -2 -3 -4 -5 ]
[ ] ]
witheach
[ dup
say "Sequence: " echo cr
maxsubseqsum
say "Subsequence: " echo cr
say "Sum: " echo cr
cr ]</syntaxhighlight>
 
{{out}}
 
<pre>Sequence: [ 1 2 3 4 5 -8 -9 -20 40 25 -5 ]
Subsequence: [ 40 25 ]
Sum: 65
 
Sequence: [ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ]
Subsequence: [ 3 5 6 -2 -1 4 ]
Sum: 15
 
Sequence: [ -1 -2 -3 -4 -5 ]
Subsequence: [ ]
Sum: 0
 
Sequence: [ ]
Subsequence: [ ]
Sum: 0
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">max.subseq <- function(x) {
cumulative <- cumsum(x)
min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
Line 2,798 ⟶ 3,189:
begin <- which.min(c(0, cumulative[1:end]))
if (end >= begin) x[begin:end] else x[c()]
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="r">> max.subseq(c(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1))
[1] 3 5 6 -2 -1 4</langsyntaxhighlight>
 
=={{header|Racket}}==
Linear time version, returns the maximum subsequence and its sum.
<langsyntaxhighlight lang="racket">
(define (max-subseq l)
(define-values (_ result _1 max-sum)
Line 2,817 ⟶ 3,208:
(values (cons i seq) max-seq (+ sum i) max-sum)])))
(values (reverse result) max-sum))
</syntaxhighlight>
</lang>
For example:
<syntaxhighlight lang="racket">
<lang Racket>
> (max-subseq '(-1 -2 3 5 6 -2 -1 4 -4 2 -1))
'(3 5 6 -2 -1 4)
15
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,831 ⟶ 3,222:
{{works with|Rakudo|2016.12}}
 
<syntaxhighlight lang="raku" perl6line>sub max-subseq (*@a) {
my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;
for @a.kv -> $i, $x {
Line 2,843 ⟶ 3,234:
}
return @a[$start ^.. $end];
}</langsyntaxhighlight>
 
Another solution, not translated from any other language:
Line 2,855 ⟶ 3,246:
The empty sequence is used to initialize $max-subset, which fulfils the "all negative" requirement of the problem.
 
<syntaxhighlight lang="raku" perl6line>sub max-subseq ( *@a ) {
 
my $max-subset = ();
Line 2,870 ⟶ 3,261:
max-subseq( -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ).say;
max-subseq( -2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1 ).say;
max-subseq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).say;</langsyntaxhighlight>
 
{{out}}
Line 2,879 ⟶ 3,270:
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">[ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] as $seq
 
1 31 shl as $max
Line 2,896 ⟶ 3,287:
#dup "$seq[%d]\n" print
$seq swap get "%d," print
$max $seq $j1 get "%d = %d\n" print</langsyntaxhighlight>
{{out}}
<pre>Sum: 3,5,6,-2,-1,4 = 15</pre>
Line 2,903 ⟶ 3,294:
===shortest greatest subsequential sum===
This REXX version will find the &nbsp; sum &nbsp; of the &nbsp; ''shortest greatest continuous subsequence''.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays the shortestlongest greatest continuous subsequence sum. */
parse arg @; w= words(@); p= w + 1 /*get arg list; number words in list. */
say 'words='w " list="@ /*show number words & LIST to terminal.,*/
sum=0; do at#=w+1 for w; @.#= word(@, #); end /*defaultbuild sum,an length,array andfor "startsfaster at"processing.*/
L=0; sum= 0 /* [↓] process the list of numbers. */
do j=1 for w; f=word(@, j) /*select one number at a time from list*/
do k=j to w; s_=f k-j+1; s= @.j /* [↓] process a sub─list of numbers. */
do m=j+1 to k; s= s +word(@, @.m); end /*m*/
if (s==sum & _>L) | s>sum then do; sum= s; atp= j; L=k-j+1 _; end
end /*k*/ /* [↑] chose the longest greatest sum of numbers. */
end /*j*/
say
$= subword(@,atp,L); if $=='' then $= "[NULL]" /*Englishize the null (value). */
say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when the following was used for the list: &nbsp; &nbsp; <tt> -1 &nbsp; -2 &nbsp; 3 &nbsp; 5 &nbsp; 6 &nbsp; -2 &nbsp; -1 &nbsp; 4 &nbsp; -4 &nbsp; 2 &nbsp; -1 </tt>}}
<pre>
words=11 list=-1 -2 3 5 6 -2 -1 4 -4 2 -1
Line 2,923 ⟶ 3,314:
sum=15 sequence=3 5 6 -2 -1 4
</pre>
'''{{out|output''' |text=&nbsp; when the following was used for the list: &nbsp; &nbsp; <tt> 1 &nbsp; 2 &nbsp; 3 &nbsp; 4 &nbsp; -777 &nbsp; 1 &nbsp; 2 &nbsp; 3 &nbsp; 4 &nbsp; 0 &nbsp; 0 </tt>}}
<pre>
words=12 list=1 2 3 4 0 -777 1 2 3 4 0 0
Line 2,932 ⟶ 3,323:
===longest greatest subsequential sum===
This REXX version will find the &nbsp; sum &nbsp; of the &nbsp; ''longest greatest continuous subsequence''.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays the longestshortest greatest continuous subsequence sum. */
parse arg @; w= words(@); p= w + 1 /*get arg list; number words in list. */
say 'words='w " list="@ /*show number words & LIST to terminal,.*/
sum=0; do at#=w+1 for w; @.#= word(@, #); end /*defaultbuild sum,an length,array andfor "startsfaster at"processing.*/
L=0; sum= 0 /* [↓] process the list of numbers. */
do j=1 for w; f=word(@,j) /*select one number at a time from list*/
do k=j to w; _s=k- @.j+1; s=f /* [↓] process a sub─list of numbers. */
do m=j+1 to k; s= s +word( @, .m); end /*m*/
if (s==sum & _>L) | s>sum then do; sum= s; atp= j; L= k - L=_j + 1; end
end /*k*/ /* [↑] chose the longest greatest sum of numbers. */
end /*j*/
say
$= subword(@,atp,L); if $=='' then $= "[NULL]" /*Englishize the null (value). */
say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when the following was used for the list: &nbsp; &nbsp; <tt> 1 &nbsp; 2 &nbsp; 3 &nbsp; 4 &nbsp; -777 &nbsp; 1 &nbsp; 2 &nbsp; 3 &nbsp; 4 &nbsp; 0 &nbsp; 0 </tt>}}
<pre>
words=12 list=1 2 3 4 0 -777 1 2 3 4 0 0
Line 2,954 ⟶ 3,345:
 
===Version 3 (translated from Pascal)===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 09.08.2012 Walter Pachl translated Pascal algorithm to Rexx
**********************************************************************/
Line 2,984 ⟶ 3,375:
Say ol
Say 'Sum:' maxSum
End</langsyntaxhighlight>
{{out}}
<pre>
Line 2,995 ⟶ 3,386:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Greatest subsequential sum
 
Line 3,044 ⟶ 3,435:
conv = left(conv, len(conv) - 2) + "]"
return conv
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,052 ⟶ 3,443:
[] - > 0
</pre>
 
=={{header|RPL}}==
{{works with|HP|48G}}
≪ DUP SIZE -> input size
≪ { }
'''CASE'''
size NOT '''THEN END''' <span style="color:grey">@ empty list case</span>
size 1 == '''THEN''' <span style="color:grey">@ singleton case</span>
'''IF''' input 1 GET 0 ≥ '''THEN''' DROP input '''END'''
'''END'''
input 0 < ΠLIST NOT '''THEN''' <span style="color:grey">@ for any list with at least 1 item > 0</span>
input ≪ MAX ≫ STREAM <span style="color:grey">@ initialize sum with maximum item</span>
+ LASTARG SWAP DROP
1 size 2 - '''FOR''' len
1 size len - '''FOR''' j
input j DUP len + SUB
DUP ∑LIST 3 PICK
'''IF''' OVER < '''THEN''' 4 ROLL 4 ROLL '''END'''
DROP2
'''NEXT NEXT'''
DROP
'''END'''
'''END'''
≫ ≫ '<span style="color:blue">BIGSUB</span>' STO
{ { -1 } { -1 2 -1 } { -1 2 -1 3 -1 } { -1 1 2 -5 -6 } { -1 -2 3 5 6 -2 -1 4 -4 2 -1 } }
1 ≪ <span style="color:blue">BIGSUB</span> ≫ DOLIST
{{out}}
<pre>
1: { { } { 2 } { 2 -1 3 } { 1 2 } { 3 5 6 -2 -1 4 } }
</pre>
===Using matrices===
{{trans|Fortran}}
{{works with|HP|49}}
≪ DUP SIZE → input size
≪ { }
'''CASE'''
size 1 == '''THEN''' <span style="color:grey">@ singleton case</span>
'''IF''' input 1 GET 0 ≥ '''THEN''' DROP input '''END'''
'''END'''
size '''THEN'''
DROP
size DUP ≪ → j k ≪ '''IF''' j k ≤ '''THEN''' input j k SUB 0 + ∑LIST '''ELSE''' 0 '''END''' ≫ ≫ LCXM
<span style="color:grey">@ forall(i=1:an,j=1:an) mix(i,j) = sum(a(i:j))</span>
OBJ→ ΠLIST →LIST DUP ≪ MAX ≫ STREAM POS <span style="color:grey">@ m = maxloc(mix)</span>
1 - size IDIV2 R→C (1,1) + input SWAP C→R SUB <span style="color:grey">@ print *, a(m(1):m(2))</span>
'''END'''
'''END'''
≫ ≫ '<span style="color:blue">BIGSUB</span>' STO
===Efficient solution===
Uses only basic RPL instructions for maximum compatibility.
{{trans|Euphoria}}
≪ DUP SIZE → s length
≪ <span style="color:red">{ }</span>
'''IF''' length '''THEN'''
<span style="color:red">0 (1 0)</span>
<span style="color:red">1</span> length '''FOR''' j
<span style="color:red">0</span>
j length '''FOR''' k
s k GET +
'''IF''' <span style="color:red">3</span> PICK OVER < '''THEN'''
ROT ROT DROP2
j k R→C OVER
'''END'''
'''NEXT''' DROP
'''NEXT''' SWAP DROP
'''IF''' DUP IM '''THEN''' s SWAP C→R SUB + '''ELSE''' DROP '''END'''
'''END'''
≫ ≫ '<span style="color:blue">BIGSUB</span>' STO
 
=={{header|Ruby}}==
===Brute Force:===
Answer is stored in "slice". It is very slow O(n**3)
<langsyntaxhighlight lang="ruby">def subarray_sum(arr)
max, slice = 0, []
arr.each_index do |i|
Line 3,065 ⟶ 3,525:
end
[max, slice]
end</langsyntaxhighlight>
'''Test:'''
<langsyntaxhighlight lang="ruby">[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
[-1, -2, -3, -4, -5],
Line 3,074 ⟶ 3,534:
puts "\nInput seq: #{input}"
puts " Max sum: %d\n Subseq: %s" % subarray_sum(input)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,097 ⟶ 3,557:
A better answer would run in O(n) instead of O(n**2) using numerical properties to remove the need for the inner loop.
 
<langsyntaxhighlight lang="ruby"># the trick is that at any point
# in the iteration if starting a new chain is
# better than your current score with this element
Line 3,118 ⟶ 3,578:
end
return max, arr[first..last]
end</langsyntaxhighlight>
The test result is the same above.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">seq$ = "-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1"
max = -999
for i = 1 to 11
Line 3,139 ⟶ 3,599:
print word$(seq$,i,",");",";
next i
print " = ";max</langsyntaxhighlight>
{{out}}
<pre>Sum: 3, 5, 6, -2, -1, 4, = 15</pre>
Line 3,145 ⟶ 3,605:
=={{header|Rust}}==
Naive brute force
<langsyntaxhighlight lang="rust">fn main() {
let nums = [1,2,39,34,20, -20, -16, 35, 0];
 
Line 3,163 ⟶ 3,623:
 
println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
}</langsyntaxhighlight>
{{out}}
<pre>Max subsequence sum: 96 for [1, 2, 39, 34, 20]</pre>
Line 3,174 ⟶ 3,634:
 
The last solution keeps to linear time by increasing complexity slightly.
<langsyntaxhighlight lang="scala">def maxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) {
case (el, acc) if acc.sum + el < 0 => Nil
case (el, acc) => el :: acc
Line 3,198 ⟶ 3,658:
case (el, (acc, ss)) => (acc + el, el :: ss)
} max Ordering.by((t: (N, List[N])) => (t._1, t._2.length)) _2
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (maxsubseq in)
(let loop
((_sum 0) (_seq (list)) (maxsum 0) (maxseq (list)) (l in))
Line 3,211 ⟶ 3,671:
(loop sum seq sum seq (cdr l))
(loop sum seq maxsum maxseq (cdr l)))
(loop 0 (list) maxsum maxseq (cdr l)))))))</langsyntaxhighlight>
 
This returns a cons of the maximum sum and (one of) the maximum subsequence(s).
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func array integer: maxSubseq (in array integer: sequence) is func
Line 3,262 ⟶ 3,722:
end for;
writeln;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,271 ⟶ 3,731:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func maxsubseq(*a) {
var (start, end, sum, maxsum) = (-1, -1, 0, 0);
a.each_kv { |i, x|
sum += x;
if (maxsum < sum) {
maxsum = sum;
end = i;
}
elsif (sum < 0) {
sum = 0;
start = i;
}
};
a.ftslice(start+1, ).first(end-start);
}
 
 
say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1);
say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1);
say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1);</langsyntaxhighlight>
 
{{out}}
Line 3,296 ⟶ 3,756:
[3, 5, 6, -1, 4]
[]
</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "gss" )
@( description, "greatest sequential sum" )
@( description, "Given a sequence of integers, find a continuous subsequence which maximizes the" )
@( description, "sum of its elements, that is, the elements of no other single subsequence add" )
@( description, "up to a value larger than this one. An empty subsequence is considered to have" )
@( description, "the sum 0; thus if all elements are negative, the result must be the empty" )
@( description, "sequence." )
@( see_also, "http://rosettacode.org/wiki/Greatest_subsequential_sum" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure gss is
 
type int_array is array( 1..11 ) of integer;
 
a : constant int_array := (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
length : constant integer := arrays.length( a );
 
beginmax : integer := 0;
endmax : integer := -1;
maxsum : integer := 0;
running_sum : integer := 0;
 
begin
 
for start in arrays.first(a)..length-1 loop
running_sum := 0;
for finish in start..length-1 loop
running_sum := @ + a(finish);
if running_sum > maxsum then
maxsum := running_sum;
beginmax := start;
endmax := finish;
end if;
end loop;
end loop;
 
for i in beginmax..endmax loop
? a(i);
end loop;
 
end gss;</syntaxhighlight>
 
=={{header|SQL}}==
{{works with|ORACLE 19c}}
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
/*
This is a code implementation for finding one or more contiguous subsequences in a general sequence with the maximum sum of its elements.
p_list -- List of elements of the general sequence of integers separated by a delimiter.
p_delimiter -- proper delimiter
*/
 
with
function greatest_subsequential_sum(p_list in varchar2, p_delimiter in varchar2) return varchar2 is
-- Variablen
v_list varchar2(32767) := trim(both p_delimiter from p_list);
v_substr_i varchar2(32767);
v_substr_j varchar2(32767);
v_substr_out varchar2(32767);
v_res integer := 0;
v_res_out integer := 0;
--
begin
--
v_list := regexp_replace(v_list,''||chr(92)||p_delimiter||'{2,}',p_delimiter);
--
for i in 1..nvl(regexp_count(v_list,'[^'||p_delimiter||']+'),0)
loop
v_substr_i := substr(v_list,regexp_instr(v_list,'[^'||p_delimiter||']+',1,i));
--
for j in reverse 1..regexp_count(v_substr_i,'[^'||p_delimiter||']+')
loop
--
v_substr_j := trim(both p_delimiter from substr(v_substr_i,1,regexp_instr(v_substr_i,'[^'||p_delimiter||']+',1,j,1)));
execute immediate 'select sum('||replace(v_substr_j,p_delimiter,'+')||') from dual' into v_res;
--
if v_res > v_res_out then
v_res_out := v_res;
v_substr_out := '{'||v_substr_j||'}';
elsif v_res = v_res_out then
v_res_out := v_res;
v_substr_out := v_substr_out||',{'||v_substr_j||'}';
end if;
--
end loop;
--
end loop;
--
v_substr_out := trim(both ',' from nvl(v_substr_out,'{}'));
v_substr_out := case when regexp_count(v_substr_out,'},{')>0 then 'subsequences '||v_substr_out else 'a subsequence '||v_substr_out end;
return 'The maximum sum '||v_res_out||' belongs to '||v_substr_out||' of the main sequence {'||p_list||'}';
end;
 
--Test
select greatest_subsequential_sum('-1|-2|-3|-4|-5|', '|') as "greatest subsequential sum" from dual
union all
select greatest_subsequential_sum('', '') from dual
union all
select greatest_subsequential_sum(' ', ' ') from dual
union all
select greatest_subsequential_sum(';;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;', ';') from dual
union all
select greatest_subsequential_sum('-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1', ',') from dual
union all
select greatest_subsequential_sum(',+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,', ',') from dual
union all
select greatest_subsequential_sum('01 +2 3 +4 05 -8 -9 -20 40 25 -5', ' ') from dual
union all
select greatest_subsequential_sum('1 2 3 0 0 -99 02 03 00001 -99 3 2 1 -99 3 1 2 0', ' ') from dual
union all
select greatest_subsequential_sum('0,0,1,0', ',') from dual
union all
select greatest_subsequential_sum('0,0,0', ',') from dual
union all
select greatest_subsequential_sum('1,-1,+1', ',') from dual;
 
</syntaxhighlight>
 
{{out}}
<pre>
The maximum sum 0 belongs to a subsequence {} of the main sequence {-1|-2|-3|-4|-5|}
The maximum sum 0 belongs to a subsequence {} of the main sequence {}
The maximum sum 0 belongs to a subsequence {} of the main sequence { }
The maximum sum 10 belongs to a subsequence {+1;2;+3;4} of the main sequence {;;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;}
The maximum sum 15 belongs to a subsequence {+3,+5,+6,-2,-1,+4} of the main sequence {-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1}
The maximum sum 19 belongs to a subsequence {+7,+4,+8} of the main sequence {,+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,}
The maximum sum 65 belongs to a subsequence {40 25} of the main sequence {01 +2 3 +4 05 -8 -9 -20 40 25 -5}
The maximum sum 6 belongs to subsequences {1 2 3 0 0},{1 2 3 0},{1 2 3},{02 03 00001},{3 2 1},{3 1 2 0},{3 1 2} of the main sequence {1 2 3 0 0 -99 02 03 00001 -99 3 2 1 -99 3 1 2 0}
The maximum sum 1 belongs to subsequences {0,0,1,0},{0,0,1},{0,1,0},{0,1},{1,0},{1} of the main sequence {0,0,1,0}
The maximum sum 0 belongs to subsequences {0,0,0},{0,0},{0},{0,0},{0},{0} of the main sequence {0,0,0}
The maximum sum 1 belongs to subsequences {1,-1,+1},{1},{+1} of the main sequence {1,-1,+1}
</pre>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val maxsubseq = let
fun loop (_, _, maxsum, maxseq) [] = (maxsum, rev maxseq)
| loop (sum, seq, maxsum, maxseq) (x::xs) = let
Line 3,316 ⟶ 3,916:
end;
 
maxsubseq [~1, ~2, 3, 5, 6, ~2, ~1, 4, ~4, 2, ~1]</langsyntaxhighlight>
This returns a pair of the maximum sum and (one of) the maximum subsequence(s).
 
=={{header|Swift}}==
{{trans|C}}
<syntaxhighlight lang="swift">func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
var maxSum = 0, thisSum = 0, i = 0
var start = 0, end = -1
for (j, seq) in sequence.enumerated() {
thisSum += seq
if thisSum < 0 {
i = j + 1
thisSum = 0
} else if (thisSum > maxSum) {
maxSum = thisSum
start = i
end = j
}
}
return start <= end && start >= 0 && end >= 0
? (start, end + 1, maxSum) : (0, 0, 0)
}
 
let a = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
let (start, end, maxSum) = maxSubseq(sequence: a)
print("Max sum = \(maxSum)")
print(a[start..<end])</syntaxhighlight>
 
{{out}}
<pre>
Max sum = 15
[3, 5, 6, -2, -1, 4]
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
set a {-1 -2 3 5 6 -2 -1 4 -4 2 -1}
 
Line 3,388 ⟶ 4,019:
puts [time {maxsumseq1 $a} 1000]
puts "maxsumseq2: [maxsumseq2 $a]"
puts [time {maxsumseq2 $a} 1000]</langsyntaxhighlight>
{{out}}
<pre>sequence: -1 -2 3 5 6 -2 -1 4 -4 2 -1
Line 3,398 ⟶ 4,029:
=={{header|Ursala}}==
This example solves the problem by the naive algorithm of testing all possible subsequences.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import int
 
Line 3,405 ⟶ 4,036:
#cast %zL
 
example = max_subsequence <-1,-2,3,5,6,-2,-1,4,-4,2,-1></langsyntaxhighlight>
The general theory of operation is as follows.
* The <code>max_subsequence</code> function is a composition of three functions, one to generate the sequences, one to sum all of them, and one to pick out the one with the maximum sum.
Line 3,420 ⟶ 4,051:
<pre>
<3,5,6,-2,-1,4></pre>
 
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="wren">var gss = Fn.new { |s|
var best = 0
var start = 0
var end = 0
var sum = 0
var sumStart = 0
var i = 0
for (x in s) {
sum = sum + x
if (sum > best) {
best = sum
start = sumStart
end = i + 1
} else if (sum < 0) {
sum = 0
sumStart = i + 1
}
i = i + 1
}
return [s[start...end], best]
}
 
var tests = [
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
[-1, 1, 2, -5, -6],
[],
[-1, -2, -1]
]
for (test in tests) {
System.print("Input: %(test)")
var res = gss.call(test)
var subSeq = res[0]
var sum = res[1]
System.print("Sub seq: %(subSeq)")
System.print("Sum: %(sum)\n")
}</syntaxhighlight>
 
{{out}}
<pre>
Input: [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
Sub seq: [3, 5, 6, -2, -1, 4]
Sum: 15
 
Input: [-1, 1, 2, -5, -6]
Sub seq: [1, 2]
Sum: 3
 
Input: []
Sub seq: []
Sum: 0
 
Input: [-1, -2, -1]
Sub seq: []
Sum: 0
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;
 
Line 3,445 ⟶ 4,134:
CrLf(0);
Text(0, "Sum = "); IntOut(0, Best); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,456 ⟶ 4,145:
=={{header|zkl}}==
{{trans|F#}}
<langsyntaxhighlight lang="zkl">fcn maxsubseq(s){
s.reduce(fcn([(sum, seq, maxsum, maxseq)], x){
sum=sum+x; seq=T(x).extend(seq);
Line 3,464 ⟶ 4,153:
},
T(0,T,0,T))[3].reverse(); // -->maxseq.reverse()
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">s:=maxsubseq(T(-1,-2,3,5,6,-2,-1,4,-4,2,-1));
println(s.sum()," : ",s);
 
s:=maxsubseq(T(-1,-2)); println(s.sum()," : ",s);
 
s:=maxsubseq(T); println(s.sum()," : ",s);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,480 ⟶ 4,169:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 DATA 12,0,1,2,-3,3,-1,0,-4,0,-1,-4,2
20 DATA 11,-1,-2,3,5,6,-2,-1,4,-4,2,-1
30 DATA 5,-1,-2,-3,-4,-5
Line 3,507 ⟶ 4,196:
260 NEXT i
270 PRINT "]"
280 NEXT n</langsyntaxhighlight>
1,983

edits