Greatest subsequential sum: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
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 40:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintArray(INT ARRAY a INT first,last)
INT i
 
Line 87:
Process(c,5)
Process(d,0)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Greatest_subsequential_sum.png Screenshot from Atari 8-bit computer]
Line 109:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Max_Subarray is
Line 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 181:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre>Max sum 15
Line 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 219:
OD
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 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 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>
Line 322:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">subarraySum: function [arr][
curr: 0
mx: 0
Line 357:
print [pad "max sum:" 15 first processed]
print [pad "subsequence:" 15 last processed "\n"]
]</langsyntaxhighlight>
 
{{out}}
Line 378:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(*
** This one is
Line 450:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 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 509:
ConsoleWrite("]" & @CRLF & "!>SUM of subsequence: " & $iSUM & @CRLF)
EndFunc ;==>GREAT_SUB
</syntaxhighlight>
</lang>
 
{{out}}
Line 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 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 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 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 624:
a$ += STR$(a%(i%)) + ", "
NEXT
= LEFT$(LEFT$(a$)) + "]"</langsyntaxhighlight>
{{out}}
<pre>
Line 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 659:
| !seq
)
</syntaxhighlight>
</lang>
 
<pre>3 5 6 -2 -1 4</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include "stdio.h"
 
typedef struct Range {
Line 711:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Max sum = 15
Line 718:
=={{header|C sharp|C#}}==
'''The challange'''
<langsyntaxhighlight lang="csharp">using System;
 
namespace Tests_With_Framework_4
Line 750:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <utility> // for std::pair
#include <iterator> // for std::iterator_traits
#include <iostream> // for std::cout
Line 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 875:
console.log max_sum_seq [-1]
console.log max_sum_seq [4, -10, 3]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 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 901:
(sum sum (- sum (first sublist))))
((or (endp sublist) (eql sum best-sum))
(values best-sum sublist start (1+ end)))))))</langsyntaxhighlight>
 
For example,
Line 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 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 977:
 
END OvctGreatestSubsequentialSum.
</syntaxhighlight>
</lang>
Execute: <br/>
<pre>
Line 993:
{{trans|Ruby}}
Answer is stored in "slice". It is very slow O(n**3)
<langsyntaxhighlight lang="ruby">def subarray_sum(arr)
max, slice = 0, [] of Int32
arr.each_index do |i|
Line 1,002:
end
[max, slice]
end</langsyntaxhighlight>
 
===Linear Time Version:===
Line 1,008:
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 1,022:
end
return max, arr[first..last]
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 1,032:
puts "\nInput seq: #{input}"
puts " Max sum: %d\n Subseq: %s" % subarray_sum(input)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,054:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio;
 
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc {
Line 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 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 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].
Line 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 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 1,190:
Indexes: ${indexes.getOptStart()}..${indexes.getOptBound().previous()}
Subsequence: ${seq(indexes.getOptStart(), indexes.getOptBound())}
`)</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'struct)
(struct result (score starter))
Line 1,229:
(max-seq L)
→ (15 (3 5 6 -2 -1 4))
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
===Linear Time Version:===
<langsyntaxhighlight lang="elixir">defmodule Greatest do
def subseq_sum(list) do
list_i = Enum.with_index(list)
Line 1,250:
{max, Enum.slice(list, first..last)}
end
end</langsyntaxhighlight>
Output is the same above.
 
===Brute Force:===
<langsyntaxhighlight lang="elixir">defmodule Greatest do
def subseq_sum(list) do
limit = length(list) - 1
Line 1,264:
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,275:
{max, subseq} = Greatest.subseq_sum(input)
IO.puts " Max sum: #{max}\n Subseq: #{inspect subseq}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,297:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM MAX_SUM
 
Line 1,365:
!$ERASE P%
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
Line 1,371:
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,395:
>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,419:
>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,432:
$ endfunction
>test
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function maxSubseq(sequence s)
integer sum, maxsum, first, last
maxsum = 0
Line 1,456:
? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1})
? maxSubseq({})
? maxSubseq({-1, -5, -3})</langsyntaxhighlight>
 
{{out}}
Line 1,464:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let maxsubseq s =
let (_, _, maxsum, maxseq) =
List.fold (fun (sum, seq, maxsum, maxseq) x ->
Line 1,474:
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,487:
: 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,515:
 
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,537:
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,575:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,585:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,620:
fmt.Println("Sum: ", sum, "\n")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,642:
=={{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,651:
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,660:
 
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,686:
}
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,710:
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,727:
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,758:
 
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,814:
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,828:
}
return maxsum;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===Imperative===
Simple brute force approach.
<langsyntaxhighlight lang="javascript">function MaximumSubsequence(population) {
var maxValue = 0;
var subsequence = [];
Line 1,857:
}
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,920:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[3,5,6,-2,-1,4] -> 15</pre>
Line 1,928:
 
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,938:
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,983:
greatestSubsequentialSum(gss) ==> [ 15, [ 3, 5, 6, -2, -1, 4 ] ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,993:
{{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 2,009:
s = sum(subseq)
 
println("Greatest subsequential sum of $arr:\n → $subseq with sum $s")</langsyntaxhighlight>
 
{{out}}
Line 2,016:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun gss(seq: IntArray): Triple<Int, Int, Int> {
Line 2,049:
else
println("Maximum subsequence is the empty sequence which has a sum of 0")
}</langsyntaxhighlight>
 
{{out}}
Line 2,059:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'Greatest_subsequential_sum
 
Line 2,112:
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 2,128:
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 2,146:
`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 2,175:
=={{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,212:
 
end;
</syntaxhighlight>
</lang>
 
produces:
 
<syntaxhighlight lang="text">
GLPSOL: GLPK LP/MIP Solver, v4.47
Parameter(s) specified in the command line:
Line 2,256:
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,273:
end;
GS = a(ix1(K)+1:ix2(K));
</syntaxhighlight>
</lang>
 
Usage:
Line 2,284:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* REXX ***************************************************************
* 10.08.2012 Walter Pachl Pascal algorithm -> Rexx -> NetRexx
**********************************************************************/
Line 2,315:
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,325:
result = max(result, maxendinghere)
 
echo maxsum(@[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])</langsyntaxhighlight>
 
{{out}}
Line 2,332:
=={{header|Oberon-2}}==
Works with oo2c Version 2
<langsyntaxhighlight lang="oberon2">
MODULE GreatestSubsequentialSum;
IMPORT
Line 2,419:
END GreatestSubsequentialSum.
 
</syntaxhighlight>
</lang>
Execute:<br/>
<pre>
Line 2,432:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let maxsubseq =
let rec loop sum seq maxsum maxseq = function
| [] -> maxsum, List.rev maxseq
Line 2,448:
 
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,476:
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,493:
);
at
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program GreatestSubsequentialSum(output);
 
var
Line 2,535:
writeln ('Sum:');
writeln (maxSum);
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./GreatestSubsequentialSum
Line 2,548:
=={{header|Perl}}==
O(n) running-sum method:
<langsyntaxhighlight lang="perl">use strict;
 
sub max_sub(\@) {
Line 2,568:
 
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,578:
 
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,596:
}
 
print "@maxsubarray\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,618:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,628:
=={{header|PHP}}==
 
<syntaxhighlight lang="php">
<lang PHP>
<?php
Line 2,667:
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}}==
Line 2,680:
===Iterative===
First build a map with all the combinations then pick the one with greatest sum.
<langsyntaxhighlight Picatlang="picat">greatest_subsequential_sum_it([]) = [] => true.
greatest_subsequential_sum_it(A) = Seq =>
P = allcomb(A),
Line 2,695:
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]).</langsyntaxhighlight>
 
===Constraint modelling===
(This was inspired by a MiniZinc model created by Claudio Cesar de Sá.)
<langsyntaxhighlight Picatlang="picat">greatest_subsequential_sum_cp([]) = [] => true.
greatest_subsequential_sum_cp(A) = Seq =>
N = A.length,
Line 2,729:
else
Seq = []
end.</langsyntaxhighlight>
 
===Test===
<langsyntaxhighlight Picatlang="picat">import cp.
 
go =>
Line 2,760:
end,
 
nl.</langsyntaxhighlight>
 
{{out}}
Line 2,784:
 
=={{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,831:
Put Edit('Sum:',maxSum)(Skip,a,f(5));
End;
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,842:
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">gss = (lst) :
# Find discrete integral
integral = (0)
Line 2,871:
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,883:
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,937:
 
memoseq(DC, LC, TTC), gss(_D, _L, TT) <=> TTC > TT |
gss(DC, LC, TTC).</langsyntaxhighlight>
{{out}}
<pre> ?- greatest_subsequence.
Line 2,948:
===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,955:
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,966:
 
=={{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 3,000:
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 3,018:
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 3,033:
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 3,048:
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 3,066:
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 3,072:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Greatest subsequential sum'''
 
from functools import (reduce)
Line 3,092:
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
)
)</langsyntaxhighlight>
{{Out}}
<pre>(15, [3, 5, 6, -2, -1, 4])</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">max.subseq <- function(x) {
cumulative <- cumsum(x)
min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
Line 3,103:
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 3,122:
(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 3,136:
{{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 3,148:
}
return @a[$start ^.. $end];
}</langsyntaxhighlight>
 
Another solution, not translated from any other language:
Line 3,160:
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 3,175:
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 3,184:
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">[ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] as $seq
 
1 31 shl as $max
Line 3,201:
#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 3,208:
===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 longest 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,*/
Line 3,221:
say
$= subword(@,p,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>
Line 3,237:
===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 shortest 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.*/
Line 3,250:
say
$= subword(@,p,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>
Line 3,259:
 
===Version 3 (translated from Pascal)===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 09.08.2012 Walter Pachl translated Pascal algorithm to Rexx
**********************************************************************/
Line 3,289:
Say ol
Say 'Sum:' maxSum
End</langsyntaxhighlight>
{{out}}
<pre>
Line 3,300:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Greatest subsequential sum
 
Line 3,349:
conv = left(conv, len(conv) - 2) + "]"
return conv
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,361:
===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,370:
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,379:
puts "\nInput seq: #{input}"
puts " Max sum: %d\n Subseq: %s" % subarray_sum(input)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,402:
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,423:
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,444:
print word$(seq$,i,",");",";
next i
print " = ";max</langsyntaxhighlight>
{{out}}
<pre>Sum: 3, 5, 6, -2, -1, 4, = 15</pre>
Line 3,450:
=={{header|Rust}}==
Naive brute force
<langsyntaxhighlight lang="rust">fn main() {
let nums = [1,2,39,34,20, -20, -16, 35, 0];
 
Line 3,468:
 
println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
}</langsyntaxhighlight>
{{out}}
<pre>Max subsequence sum: 96 for [1, 2, 39, 34, 20]</pre>
Line 3,479:
 
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,503:
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,516:
(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,567:
end for;
writeln;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,576:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func maxsubseq(*a) {
var (start, end, sum, maxsum) = (-1, -1, 0, 0);
a.each_kv { |i, x|
Line 3,594:
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,607:
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
<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.
Line 3,678:
select greatest_subsequential_sum('1,-1,+1', ',') from dual;
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,696:
 
=={{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,713:
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}}
<langsyntaxhighlight lang="swift">func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
var maxSum = 0, thisSum = 0, i = 0
var start = 0, end = -1
Line 3,739:
let (start, end, maxSum) = maxSubseq(sequence: a)
print("Max sum = \(maxSum)")
print(a[start..<end])</langsyntaxhighlight>
 
{{out}}
Line 3,748:
 
=={{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,816:
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,826:
=={{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,833:
#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,850:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;
 
Line 3,873:
CrLf(0);
Text(0, "Sum = "); IntOut(0, Best); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,884:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight lang="ecmascript">var gss = Fn.new { |s|
var best = 0
var start = 0
Line 3,919:
System.print("Sub seq: %(subSeq)")
System.print("Sum: %(sum)\n")
}</langsyntaxhighlight>
 
{{out}}
Line 3,942:
=={{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,950:
},
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,966:
=={{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,993:
260 NEXT i
270 PRINT "]"
280 NEXT n</langsyntaxhighlight>
10,333

edits