天天看點

[LeetCode] Best Time to Buy and Sell Stock II

say you have an array for which the ith element is the price of a given stock on day i.

design an algorithm to find the maximum profit. you may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). however, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

與版本1的題目相比,本題的差別在于允許多次交易,是以最大收益等于每對極大值與極小值的內插補點之和(每次在極小值點買入,極大值點賣出)。

首先将買入價格設定為<code>prices[0]</code>,然後周遊數組,如果目前元素的值大于等于下一個元素(該元素為極大值點),則将該元素的值與買入價格的內插補點加到總收益中,同時,将買入價格設定為該元素的下一個元素(在價格跌落時,目前元素值與買入價格之差為0)。