Skip to content

Commit b81a3f6

Browse files
committed
Put comments in Kadane's algo and added functional version in Ruby
1 parent bb519a7 commit b81a3f6

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

Maximum_Subarray/Ruby/jcla1/maximum_subarray.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,24 @@ def maximum_subarray(arr)
55

66
cur_max, max_so_far = arr.first, arr.first
77

8+
# arr[1..-1] is getting everything,
9+
# but the first element of the array.
10+
# It is equivalent to (cdr arr) in Lisp/Scheme etc.
811
arr[1..-1].each do |v|
912
cur_max = [cur_max+v, v].max
1013
max_so_far = [cur_max, max_so_far].max
1114
end
1215

16+
# Ruby automatically returns the last evaluated
17+
# expression, so we've no need for return
1318
max_so_far
19+
end
20+
21+
22+
def maximum_subarray_functional(arr)
23+
# This is the functional one-liner of Kadane's algorithm
24+
# The accumulator in reduce is an array containing:
25+
# [0] - maximum sum so far
26+
# [1] - current maximum streak
27+
arr[1..-1].reduce([arr[0], arr[0]]) { |mem, n| c = [n, mem[1]+n].max; [[mem[0], c].max, c] }[0]
1428
end

0 commit comments

Comments
 (0)