Greatest subsequential sum: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|SQL}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 12:
{{trans|Python}}
<
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]))</
{{out}}
Line 40:
=={{header|Action!}}==
<
INT i
Line 87:
Process(c,5)
Process(d,0)
RETURN</
{{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}}==
<
procedure Max_Subarray is
Line 146:
when Empty_Error =>
Put_Line("Array being analyzed has no elements.");
end Max_Subarray;</
=={{header|Aime}}==
<
{
integer e, f, i, sum;
Line 181:
0;
}</
{{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]}}
<
(
[]INT a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
Line 219:
OD
)</
{{out}}
<pre>
Line 228:
{{Trans|Haskell}}
Linear derivation of both sum and list, in a single fold:
<
on maxSubseq(xs)
script go
Line 316:
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple</
{{Out}}
<pre>{15, {3, 5, 6, -2, -1, 4}}</pre>
Line 322:
=={{header|Arturo}}==
<
curr: 0
mx: 0
Line 357:
print [pad "max sum:" 15 first processed]
print [pad "subsequence:" 15 last processed "\n"]
]</
{{out}}
Line 378:
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(*
** This one is
Line 450:
//
} (* end of [main0] *)
</syntaxhighlight>
{{out}}
<pre>
Line 459:
=={{header|AutoHotkey}}==
classic algorithm:
<
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) "]"</
=={{header|AutoIt}}==
<syntaxhighlight 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>
{{out}}
Line 524:
=={{header|AWK}}==
{{trans|Common Lisp}}
<
# 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
}</
Demonstration: <
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")
}</
{{out}}
Line 589:
=={{header|BBC BASIC}}==
<
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$)) + "]"</
{{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>.
<
( 0:?max
& :?seq
Line 659:
| !seq
)
</syntaxhighlight>
<pre>3 5 6 -2 -1 4</pre>
=={{header|C}}==
<
typedef struct Range {
Line 711:
return 0;
}</
{{out}}
<pre>Max sum = 15
Line 718:
=={{header|C sharp|C#}}==
'''The challange'''
<
namespace Tests_With_Framework_4
Line 750:
}
}
}</
=={{header|C++}}==
<
#include <iterator> // for std::iterator_traits
#include <iostream> // for std::cout
Line 841:
return 0;
}</
=={{header|Clojure}}==
{{trans|Haskell}}
Naive algorithm:
<
(->> (take-while seq (iterate rest coll)) ; tails
(mapcat #(reductions conj [] %)) ; inits
(apply max-key #(reduce + %)))) ; max sum</
{{out}}
<
[3 5 6 -2 -1 4]</
=={{header|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>
=={{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.
<
(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)))))))</
For example,
Line 921:
{{trans|PicoLisp}}
<
(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))))</
=={{header|Component Pascal}}==
Works with BlackBox Component Builder
<
MODULE OvctGreatestSubsequentialSum;
IMPORT StdLog, Strings, Args;
Line 977:
END OvctGreatestSubsequentialSum.
</syntaxhighlight>
Execute: <br/>
<pre>
Line 993:
{{trans|Ruby}}
Answer is stored in "slice". It is very slow O(n**3)
<
max, slice = 0, [] of Int32
arr.each_index do |i|
Line 1,002:
end
[max, slice]
end</
===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.
<
# 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</
'''Test:'''
<
[-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</
{{out}}
<pre>
Line 1,054:
=={{header|D}}==
{{trans|Python}}
<
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);
}</
{{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).
<
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;
}</
=={{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.
<
def maxSubseq(seq) {
Line 1,181:
return ["value" => maxValue,
"indexes" => maxInterval]
}</
<
def [=> value, => indexes] := maxSubseq(seq)
println(`$\
Line 1,190:
Indexes: ${indexes.getOptStart()}..${indexes.getOptBound().previous()}
Subsequence: ${seq(indexes.getOptStart(), indexes.getOptBound())}
`)</
=={{header|EchoLisp}}==
<
(lib 'struct)
(struct result (score starter))
Line 1,229:
(max-seq L)
→ (15 (3 5 6 -2 -1 4))
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Ruby}}
===Linear Time Version:===
<
def subseq_sum(list) do
list_i = Enum.with_index(list)
Line 1,250:
{max, Enum.slice(list, first..last)}
end
end</
Output is the same above.
===Brute Force:===
<
def subseq_sum(list) do
limit = length(list) - 1
Line 1,264:
end)
end
end</
'''Test:'''
<
[-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)</
{{out}}
Line 1,297:
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM MAX_SUM
Line 1,365:
!$ERASE P%
END PROGRAM
</syntaxhighlight>
=={{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">
>function %maxsubs (v,n) ...
$if n==1 then
Line 1,395:
>maxsubs([-1, -2, -3, -4, -5])
Empty matrix of size 1x0
</syntaxhighlight>
Here is a brute force method producing and testing all sums. The runtime is O(n^3).
<syntaxhighlight 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>
To see, if everything works, the following tests on 10 million random sequences.
<syntaxhighlight lang="euler math toolbox">
>function test ...
$ loop 1 to 10000000
Line 1,432:
$ endfunction
>test
</syntaxhighlight>
=={{header|Euphoria}}==
<
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})</
{{out}}
Line 1,464:
=={{header|F_Sharp|F#}}==
<
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])</
{{out}}
<pre>[3; 5; 6; -2; -1; 4]</pre>
=={{header|Factor}}==
<
:: 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 ;</
<
{ 3 5 6 -2 -1 4 }
15</
=={{header|Forth}}==
<
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 ,</
{{out}}
<
test2 11 max-sub .array [3 5 6 -2 -1 4 -4 2 99 ] = 112 ok</
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,537:
print *, a(m(1):m(2))
end program MaxSubSeq</
=={{header|FreeBASIC}}==
<
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</
{{out}}
Line 1,585:
=={{header|Go}}==
<
import "fmt"
Line 1,620:
fmt.Println("Sum: ", sum, "\n")
}
}</
{{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:
<
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]</
Secondly, the linear time constant space approach:
<
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]</
{{Out}}
<pre>(15,[3,5,6,-2,-1,4])</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
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</
=={{header|IS-BASIC}}==
<
110 RANDOMIZE
120 NUMERIC A(1 TO 15)
Line 1,710:
290 PRINT A(I);
300 NEXT
310 PRINT :PRINT "Sum:";MAXSUM</
=={{header|J}}==
<
AS =. 0,; <:/~@i.&.> #\y
MX =. (= >./) AS +/ . * y
y #~ {. MX#AS
)</
<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:
<
3 5 6 _2 _1 4</
Note: if we just want the sum of the maximum subsequence,
and are not concerned with the subsequence itself, we can use:
<
Example use:
<
15</
This suggests a variant:
<
sums=: (0>.+)/\. y
start=: sums i. max=: >./ sums
max (] {.~ #@] |&>: (= +/\) i. 1:) y}.~start
)</
or
<
start=. (i. >./) (0>.+)/\. y
({.~ # |&>: [: (i.>./@,&0) +/\) y}.~start
)</
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].
<
import java.util.ArrayList;
Line 1,814:
return false;
}
}</
This one runs in linear time, and isn't generalized.
<
int sum = 0;
int maxsum = 0;
Line 1,828:
}
return maxsum;
}</
=={{header|JavaScript}}==
===Imperative===
Simple brute force approach.
<
var maxValue = 0;
var subsequence = [];
Line 1,857:
}
return result;
}</
===Functional===
{{Trans|Haskell}}
Linear approach, deriving both list and sum in a single accumulating fold.
<
// maxSubseq :: [Int] -> (Int, [Int])
Line 1,920:
// MAIN ---
return main();
})();</
{{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.
<
. as $arr
| reduce range(0; length) as $i
Line 1,938:
else .
end)
| [ .max, $arr[ .first : (1 + .last)] ];</
'''Example''':
<
{{out}}
<
[65,[40,25]]</
=={{header|Jsish}}==
From Javascript entry.
<
function sumValues(arr) {
var result = 0;
Line 1,983:
greatestSubsequentialSum(gss) ==> [ 15, [ 3, 5, 6, -2, -1, 4 ] ]
=!EXPECTEND!=
*/</
{{out}}
Line 1,993:
{{works with|Julia|0.6}}
<
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")</
{{out}}
Line 2,016:
=={{header|Kotlin}}==
<
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")
}</
{{out}}
Line 2,059:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'Greatest_subsequential_sum
Line 2,112:
print
end sub
</
=={{header|Lua}}==
<
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</
=={{header|M4}}==
<
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) ')</
=={{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.
<
MaximumSubsequence[x_List]:=Module[{sums},
sums={x[[#]],Total[x[[#]]]}&/@Sequences[Length[x]];
First[First[sums[[Ordering[sums,-1,#1[[2]]<#2[[2]]&]]]]]
]</
===Method 2===
<
===Examples===
<
MaximumSubsequence[{2,4,5}]
MaximumSubsequence[{2,-4,3}]
MaximumSubsequence[{4}]
MaximumSubsequence[{}]</
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>
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>
=={{header|MATLAB}} / {{header|Octave}}==
<
% Greatest subsequential sum
a =[0;a(:);0]';
Line 2,273:
end;
GS = a(ix1(K)+1:ix2(K));
</syntaxhighlight>
Usage:
Line 2,284:
=={{header|NetRexx}}==
<
* 10.08.2012 Walter Pachl Pascal algorithm -> Rexx -> NetRexx
**********************************************************************/
Line 2,315:
Say ol
Say 'Sum:' maxSum
End</
Output: the same as for Rexx
=={{header|Nim}}==
<
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])</
{{out}}
Line 2,332:
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE GreatestSubsequentialSum;
IMPORT
Line 2,419:
END GreatestSubsequentialSum.
</syntaxhighlight>
Execute:<br/>
<pre>
Line 2,432:
=={{header|OCaml}}==
<
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]</
This returns a pair of the maximum sum and (one of) the maximum subsequence(s).
=={{header|Oz}}==
<
fun {MaxSubSeq Xs}
Line 2,476:
end
in
{Show {MaxSubSeq [~1 ~2 3 5 6 ~2 ~1 4 ~4 2 1]}}</
=={{header|PARI/GP}}==
Naive quadratic solution (with end-trimming).
<
my(mn=1,mx=#v,r=0,at,c);
if(vecmax(v)<=0,return([1,0]));
Line 2,493:
);
at
};</
=={{header|Pascal}}==
<
var
Line 2,535:
writeln ('Sum:');
writeln (maxSum);
end.</
{{out}}
<pre>:> ./GreatestSubsequentialSum
Line 2,548:
=={{header|Perl}}==
O(n) running-sum method:
<
sub max_sub(\@) {
Line 2,568:
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n";</
{{out}}
<pre>
Line 2,578:
Naive and potentionally very slow method:
<
my @a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);
Line 2,596:
}
print "@maxsubarray\n";</
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,628:
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
Line 2,667:
print_array(max_sum_seq(array(4, -10, 3)));
?>
</syntaxhighlight>
{{out}} in browser:
<syntaxhighlight lang="text">
0 15 3 -9 12
(empty)
4
</syntaxhighlight>
=={{header|Picat}}==
Line 2,680:
===Iterative===
First build a map with all the combinations then pick the one with greatest sum.
<
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]).</
===Constraint modelling===
(This was inspired by a MiniZinc model created by Claudio Cesar de Sá.)
<
greatest_subsequential_sum_cp(A) = Seq =>
N = A.length,
Line 2,729:
else
Seq = []
end.</
===Test===
<
go =>
Line 2,760:
end,
nl.</
{{out}}
Line 2,784:
=={{header|PicoLisp}}==
<
(mapcon '((L) (maplist reverse (reverse L)))
(-1 -2 3 5 6 -2 -1 4 -4 2 -1) ) )</
{{out}}
<pre>-> (3 5 6 -2 -1 4)</pre>
=={{header|PL/I}}==
<
ss: Proc Options(Main);
/* REXX ***************************************************************
Line 2,831:
Put Edit('Sum:',maxSum)(Skip,a,f(5));
End;
End;</
{{out}}
<pre>
Line 2,842:
=={{header|Potion}}==
<
# 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))</
<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'''.
<
:- chr_constraint
Line 2,937:
memoseq(DC, LC, TTC), gss(_D, _L, TT) <=> TTC > TT |
gss(DC, LC, TTC).</
{{out}}
<pre> ?- greatest_subsequence.
Line 2,948:
===Brute Force===
Works with [https://rosettacode.org/wiki/GNU_Prolog GNU Prolog].
<
maxsubseq(List, Sub, Sum) :-
Line 2,955:
max_list(Sums, Sum),
nth(N, Sums, Sum),
nth(N, Subs, Sub).</
{{out}}
<pre>| ?- maxsubseq([-1,-2,3,5,6,-2,-1,4,-4,2,-1], Sub, Sum).
Line 2,966:
=={{header|PureBasic}}==
<
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</
=={{header|Python}}==
===Imperative===
Naive, inefficient but really simple solution which tests all possible subsequences, as in a few of the other examples:
<
return max((seq[begin:end] for begin in xrange(len(seq)+1)
for end in xrange(begin, len(seq)+1)),
key=sum)</
Classic linear-time constant-space solution based on algorithm from "Programming Pearls" book.
<
"""Return maximum sum."""
maxsofar, maxendinghere = 0, 0
Line 3,018:
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar</
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
<
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]</
Modify ``maxsumseq()`` to allow any iterable not just sequences.
<
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]</
Elementary tests:
<
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]</
===Functional===
Line 3,072:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<
from functools import (reduce)
Line 3,092:
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
)
)</
{{Out}}
<pre>(15, [3, 5, 6, -2, -1, 4])</pre>
=={{header|R}}==
<
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()]
}</
{{out}}
<
[1] 3 5 6 -2 -1 4</
=={{header|Racket}}==
Linear time version, returns the maximum subsequence and its sum.
<
(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>
For example:
<syntaxhighlight lang="racket">
> (max-subseq '(-1 -2 3 5 6 -2 -1 4 -4 2 -1))
'(3 5 6 -2 -1 4)
15
</syntaxhighlight>
=={{header|Raku}}==
Line 3,136:
{{works with|Rakudo|2016.12}}
<syntaxhighlight lang="raku"
my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;
for @a.kv -> $i, $x {
Line 3,148:
}
return @a[$start ^.. $end];
}</
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"
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;</
{{out}}
Line 3,184:
=={{header|Raven}}==
<
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</
{{out}}
<pre>Sum: 3,5,6,-2,-1,4 = 15</pre>
Line 3,208:
===shortest greatest subsequential sum===
This REXX version will find the sum of the ''shortest greatest continuous subsequence''.
<
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. */</
{{out|output|text= when the following was used for the list: <tt> -1 -2 3 5 6 -2 -1 4 -4 2 -1 </tt>}}
<pre>
Line 3,237:
===longest greatest subsequential sum===
This REXX version will find the sum of the ''longest greatest continuous subsequence''.
<
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. */</
{{out|output|text= when the following was used for the list: <tt> 1 2 3 4 -777 1 2 3 4 0 0 </tt>}}
<pre>
Line 3,259:
===Version 3 (translated from Pascal)===
<
* 09.08.2012 Walter Pachl translated Pascal algorithm to Rexx
**********************************************************************/
Line 3,289:
Say ol
Say 'Sum:' maxSum
End</
{{out}}
<pre>
Line 3,300:
=={{header|Ring}}==
<
# Project : Greatest subsequential sum
Line 3,349:
conv = left(conv, len(conv) - 2) + "]"
return conv
</syntaxhighlight>
Output:
<pre>
Line 3,361:
===Brute Force:===
Answer is stored in "slice". It is very slow O(n**3)
<
max, slice = 0, []
arr.each_index do |i|
Line 3,370:
end
[max, slice]
end</
'''Test:'''
<
[-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</
{{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.
<
# 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</
The test result is the same above.
=={{header|Run BASIC}}==
<
max = -999
for i = 1 to 11
Line 3,444:
print word$(seq$,i,",");",";
next i
print " = ";max</
{{out}}
<pre>Sum: 3, 5, 6, -2, -1, 4, = 15</pre>
Line 3,450:
=={{header|Rust}}==
Naive brute force
<
let nums = [1,2,39,34,20, -20, -16, 35, 0];
Line 3,468:
println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
}</
{{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.
<
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
}</
=={{header|Scheme}}==
<
(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)))))))</
This returns a cons of the maximum sum and (one of) the maximum subsequence(s).
=={{header|Seed7}}==
<
const func array integer: maxSubseq (in array integer: sequence) is func
Line 3,567:
end for;
writeln;
end func;</
{{out}}
<pre>
Line 3,576:
=={{header|Sidef}}==
{{trans|Raku}}
<
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);</
{{out}}
Line 3,607:
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.
Line 3,678:
select greatest_subsequential_sum('1,-1,+1', ',') from dual;
</syntaxhighlight>
{{out}}
Line 3,696:
=={{header|Standard ML}}==
<
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]</
This returns a pair of the maximum sum and (one of) the maximum subsequence(s).
=={{header|Swift}}==
{{trans|C}}
<
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])</
{{out}}
Line 3,748:
=={{header|Tcl}}==
<
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]</
{{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.
<
#import int
Line 3,833:
#cast %zL
example = max_subsequence <-1,-2,3,5,6,-2,-1,4,-4,2,-1></
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}}==
<
int Array, Size, Sum, Best, I, Lo, Hi, BLo, BHi;
Line 3,873:
CrLf(0);
Text(0, "Sum = "); IntOut(0, Best); CrLf(0);
]</
{{out}}
Line 3,884:
=={{header|Wren}}==
{{trans|Go}}
<
var best = 0
var start = 0
Line 3,919:
System.print("Sub seq: %(subSeq)")
System.print("Sum: %(sum)\n")
}</
{{out}}
Line 3,942:
=={{header|zkl}}==
{{trans|F#}}
<
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()
}</
<
println(s.sum()," : ",s);
s:=maxsubseq(T(-1,-2)); println(s.sum()," : ",s);
s:=maxsubseq(T); println(s.sum()," : ",s);</
{{out}}
<pre>
Line 3,966:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<
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</
|