Skip to content

Commit a25b824

Browse files
committed
Lesson 7 - MaxProfit (from scratch)
1 parent 7824d35 commit a25b824

File tree

1 file changed

+5
-10
lines changed

1 file changed

+5
-10
lines changed

max_profit.rb

+5-10
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
def max_profit(a)
2-
min_price = a[0]
3-
a = a.drop(1)
42
max_profit = 0
3+
min_price = 1 / 0.0
54

6-
a.each do |price|
7-
if price < min_price
8-
min_price = price
9-
next
10-
end
11-
profit = price - min_price
12-
max_profit = profit if profit > max_profit
5+
a.each do |v|
6+
min_price = [min_price, v].min
7+
max_profit = [max_profit, v - min_price].max
138
end
149

1510
max_profit
@@ -23,6 +18,6 @@ def test_example_input
2318
end
2419

2520
def test_no_profit
26-
assert_equal 0, max_profit([100, 1])
21+
assert_equal 0, max_profit([10, 5, 1])
2722
end
2823
end

0 commit comments

Comments
 (0)