LeetCode 122.买卖股票的最佳时机2

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii
给定一个数组 prices ,其中 prices[i] 表示股票第 i 天的价格。

在每一天,你可能会决定购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以购买它,然后在 同一天 出售。
返回 你能获得的 最大 利润 。

思路:
一:动态规划
在第i天,分为持有股票和不持有股票两种情况,用dp[i][0]和dp[i][1]表示;
如果第i天不持有股票,那么可能是第i - 1天也不持有股票,也可能是第i - 1天持有股票而第i天卖出了,那么利润为二者中的最大值;
如果第i天持有股票,那么有可能是第i - 1天也持有股票,也可能是第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]);

var maxProfit = function(prices) {
    const len = prices.length;
    let dp = new Array(len).fill(0).map( () => new Array(2).fill(0) );
    dp[0][0] = 0;
    dp[0][1] = -prices[0];
    for (let i = 1; i < len; 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 dp[len - 1][0];
};

状态压缩:

var maxProfit = function(prices) {
    const len = prices.length;
    let sell = 0;
    let buy = -prices[0];
    for (let i = 1; i < len; i++) {
        let temp = sell;
        sell = Math.max(sell, buy + prices[i]);
        buy = Math.max(buy, temp - prices[i]);
    }

    return sell;
};

二:贪心算法
如果股票第二天比前一天是上涨的,则进行买卖,否则就不买卖,即每次都取有利润的买卖,即可获得最大利润。

var maxProfit = function(prices) {
    let bene = 0
    for(let i = 1; i < prices.length; i++) {
        bene += Math.max(0, prices[i] - prices[i - 1])
    }
    return bene
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值