Skip to content

Commit fd74e48

Browse files
authored
Add Maximum Subarray in Tcl (#5069)
1 parent 53649d3 commit fd74e48

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

archive/t/tcl/maximum-subarray.tcl

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
proc usage {} {
2+
puts stderr {Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"}
3+
exit 1
4+
}
5+
6+
proc parseList {s} {
7+
set tokens [split [string trim $s] ","]
8+
if {[llength $tokens] < 1} { usage }
9+
10+
set result {}
11+
12+
set result {}
13+
foreach token $tokens {
14+
set t [string trim $token]
15+
if {$t eq "" || [catch {expr {int($t)}} val]} usage
16+
lappend result $val
17+
}
18+
return $result
19+
}
20+
21+
proc maximumSubarraySum {numbers} {
22+
if {[llength $numbers] == 0} { return 0 }
23+
24+
set currentSum [lindex $numbers 0]
25+
set maxSum $currentSum
26+
27+
for {set i 1} {$i < [llength $numbers]} {incr i} {
28+
set val [lindex $numbers $i]
29+
set currentSum [expr {max($val, $currentSum + $val)}]
30+
set maxSum [expr {max($maxSum, $currentSum)}]
31+
}
32+
33+
return $maxSum
34+
}
35+
36+
if {$argc != 1} { usage }
37+
38+
set numbers [parseList [lindex $argv 0]]
39+
puts [maximumSubarraySum $numbers]

0 commit comments

Comments
 (0)