I have a question about the solution to 6.8 “Buy and Sell a Stock Twice”. I understand that the problem can be completed in O(n) time, but I don’t see why you need two traversals through the array. The way I solved it was to maintain an array of the highest profit seen so far at each i, the index of the minimum so far and the overall profit. My traversal, in ruby, looks like this:
(1...array.size).each do |i|
current_profit = array[i] - min_value
profits[i] = [current_profit, profits[i-1]].max
previous_max = profits[min_index]
overall_profit = [current_profit + previous_max, overall_profit].max
if array[i] < array[min_index]
min_index = i
end
end
The general approach is to calculate the profit at each i and then add the best profit before the current min_index. Is there a case that breaks my solution?