Skip to content

Commit 7824d35

Browse files
committed
Lesson 7 - MaxDoubleSliceSum (from scratch)
1 parent ca7d512 commit 7824d35

File tree

1 file changed

+26
-20
lines changed

1 file changed

+26
-20
lines changed

max_double_slice.rb

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,29 @@
1-
# based on: http://stackoverflow.com/questions/20660989/max-double-slice-sum/20661624#20661624
2-
# solved with banging my head against the wall
31
def max_double_slice(a)
4-
max_double_slice = 0
5-
max_sum_ending_at = []
6-
max_sum_starting_from = []
7-
8-
a[0] = a[-1] = 0
2+
a[0] = 0
3+
a[-1] = 0
94

10-
max_sum_ending_at = max_sum_ending_at_for(a)
11-
max_sum_starting_from = max_sum_ending_at_for(a.reverse).reverse
12-
13-
for i in 1..(a.size-2)
14-
current_double_slice = max_sum_ending_at[i-1] + max_sum_starting_from[i+1]
15-
max_double_slice = current_double_slice if current_double_slice > max_double_slice
5+
max_from_left = []
6+
max_ending = 0
7+
a.each do |v|
8+
max_ending = [0, max_ending + v].max
9+
max_from_left << max_ending
1610
end
17-
max_double_slice
18-
end
1911

20-
def max_sum_ending_at_for(array)
12+
max_from_right = []
2113
max_ending = 0
22-
array.each_with_index.map do |v, i|
23-
max_ending = 0 > max_ending + v ? 0 : max_ending + v
14+
a.reverse.each do |v|
15+
max_ending = [0, max_ending + v].max
16+
max_from_right << max_ending
2417
end
18+
max_from_right.reverse!
19+
20+
n = a.size
21+
max_double_slice = 0
22+
for i in 1..n-2
23+
max_double_slice = [max_double_slice, max_from_left[i - 1] + max_from_right[i + 1]].max
24+
end
25+
26+
max_double_slice
2527
end
2628

2729
require 'minitest/autorun'
@@ -31,7 +33,11 @@ def test_example_input
3133
assert_equal 17, max_double_slice([3, 2, 6, -1, 4, 5, -1, 2])
3234
end
3335

34-
def test_successive_negative_numbers
35-
assert_equal 1, max_double_slice([0, 1, -10, -10, -100, 1, 9])
36+
def test_negative_numbers
37+
assert_equal 0, max_double_slice([-1, -1, -1, -10, -4])
38+
end
39+
40+
def test_three_values
41+
assert_equal 0, max_double_slice([10, 20, 30])
3642
end
3743
end

0 commit comments

Comments
 (0)