leetcode 买卖股票的最佳时机 II

162 阅读1分钟

122. 买卖股票的最佳时机 II

leetcode-cn.com/problems/be…

  • 单调栈 构建一个单调递增的栈
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let sum = 0

    let stack = []
    for (let i = 0; i < prices.length; i++) {
        while (prices[i] < stack[stack.length - 1]) {
            const curr = stack.pop()
            if (stack.length) {
                sum = sum + (curr - stack[0])
            }
            stack = []
        }
        stack.push(prices[i])
    }
    if (stack.length) {

        sum = sum + (stack[stack.length - 1] - stack[0])
    }
    return sum
};
  • 动态规划 考虑第i天是否持有股票 构建二维数组存储第i天持有或不持有股票的收益
/**
 * @param {number[]} prices
 * @return {number}
 */
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let sum = 0
    const dp = prices.map(i=>[])
    dp[0][1] = -prices[0]
    dp[0][0] = 0
    for(let i=1;i<prices.length;i++){
        dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i])
        dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0] - prices[i])
    }
    return Math.max(...dp[prices.length-1])
};