面試題63:股票的最大利潤
一、題目描述
假設把某股票的價格按照時間先後順序存儲在數組中,請問買賣交易該股票可能獲得的利潤是多少?例如一隻股票在某些時間節點的價格爲{9, 11, 8, 5,7, 12, 16, 14}。如果我們能在價格爲5的時候買入並在價格爲16時賣出,則能收穫最大的利潤11。
二、問題分析
這道題很容易想到貪心算法:遍歷每一個數字,並保存之前最小的數字,兩者差最大即爲最大利潤。
不過這也有一個數學模型,叫做峯谷求值
專注點在於這種圖表的連續的峯和谷。
更多的情況是關注它的差值:
用數學語言描述爲:
三、問題解決
public int maxProfit(int[] prices) {
int i = 0;
int valley = prices[0];
int peak = prices[0];
int maxprofit = 0;
while (i < prices.length - 1) {
while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i + 1]) {
i++;
}
peak = prices[i];
maxprofit += peak - valley;
}
return maxprofit;
}