DP、贪心-LeetCode122. 买卖股票的最佳时机 II(k = +infinity)

1、题目描述

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。  

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易 k = +infinity(多次买卖一支股票)。

 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

2、贪心法,易懂建议

如果今天的价格比明天的价格低,就今天买,明天卖(贪心)

class Solution(object):
    def maxProfit(self, prices):
        n = len(prices)
        if n == 0:
            return 0
        res = 0
        for i in range(1, n):
            if prices[i] - prices[i-1] > 0:
                res += prices[i] - prices[i-1]
        return res

3、通用版代码详解

同类型题 DP-LeetCode121. 买卖股票的最佳时机

class Solution(object):
    def maxProfit(self, prices):
        # dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
        # dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
        n = len(prices)
        dp_i_0 = 0
        dp_i_1 = float("-inf")
        for i in range(n):
            temp = dp_i_0
            dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
            dp_i_1 = max(dp_i_1, temp - prices[i])
        return dp_i_0
prices = [7,1,5,3,6,4]
s = Solution()
print(s.maxProfit(prices))

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-l-3/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值