I'm trying to understand a solution that I found for the following leetCode problem.
Description: "You are given an array of prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. "
Explanation: "Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell."
And I came across this solution that I'm trying to understand. Breaking it down at "->":
def max_profit([7,1,5,3,6,4])
value = 0
profit = 0
(1...prices.size).each do |i|
value += (prices[i] - prices[i-1])
-> So here value = 0 + (1-7 = -6)= -6 /value = -6 + (5-1=4)= -2 / value = -2+(3-5)=-4 and so on ending in -3
value = [0, value].max
-> This is what I don't get. Now value = [0, value].max and when I print it I get 0,4,2,5,3.
The way I'm seeing this is: (in the first iteration) value = [0, -6].max, so value is 0 because 0 > than -6
but then I get 4 for the second iteration when value = [0, -2].max ... Shouldn't it be 0 again?? How am getting 0,4,2,5,3 ???
What actually happens when I do value = [0, value].max. ?
profit = value if value > profit
end
profit
end
A million thanks