首先,我们想到直观解法,即计算出第 i 天买入,后续所有可能卖出情况下的收益,取最大值即为第 i 天买入可获得的最大收益。
然后比较每一天的最大收益,取最大值,即可得出所有操作中能获取的最大收益。
详解
假设第 i 天当天买入,依次遍历第 i 天之后的所有可能卖出的情况,比较得出收益中的最大值 max。 假设 maxProfit 为当前可以获得的最大收益,初始值为 0,将第 i 天买入收益最大值 max 与 maxProfit 比较,如果 max > maxProfit 则更新 maxProfit 的值,依次进行,最终得到最大收益。
代码
1
/**
2
* @param {number[]} prices
3
* @return {number}
4
*/
5
functionmaxProfit(prices){
6
let maxProfit =0;
7
8
functiongetMax(i){// 获取第 i 天后股票价格中的最大值
9
let max = prices[i +1];
10
11
for(let j = i +1; j < prices.length; j++){
12
if(prices[j]> max){
13
max = prices[j];
14
}
15
}
16
17
return max;
18
}
19
20
for(i =0; i < prices.length -1; i++){
21
const max =getMax(i)- prices[i];// 记录第 i 天买入后续合理时间卖出可获得的最大收益