题解 | 买卖股票的最好时机(二)
买卖股票的最好时机(二)
https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 计算最大收益
* @param prices int整型一维数组 股票每一天的价格
* @return int整型
*/
function maxProfit( prices ) {
// 0 没持有股票
// 1 持有股票
const n = prices.length
let max = 0
const dp = [0, -prices[0]]
for (let i = 1; i < n; i++) {
const [a, b] = dp
// 持有,可能是之前就持有,也可能是现在持有
dp[1] = Math.max(b, a - prices[i])
// 未持有,可能是之前就未持有,也可能是当前卖了
dp[0] = Math.max(a, b + prices[i])
max = Math.max(max, dp[0])
}
return max
}
module.exports = {
maxProfit : maxProfit
};