leetcode122. Best Time to Buy and Sell Stock II (买卖股票的最佳时机 II)

题目要求

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意区别 leetcode 121 Best Time to Buy and Sell Stock(最大盈利)
第一题是进行一次交易。本题是多次交易
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

补充 股票四连合集,看了不亏,没看后悔!!:

NO.1 leetcode 121 Best Time to Buy and Sell Stock(买卖股票的最佳时机)
NO.2 leetcode122. Best Time to Buy and Sell Stock II (买卖股票的最佳时机 II)
NO.3 leetcode123. Best Time to Buy and Sell Stock III( 买卖股票的最佳时机 III)
NO.4 leetcode188. Best Time to Buy and Sell Stock IV(买卖股票的最佳时机 IV)

解题思路

考虑买股票的策略:设今天价格p1,明天价格p2,若p1 < p2则今天买入明天卖出,赚取p2 - p1;
若遇到连续上涨的交易日,第一天买最后一天卖收益最大,等价于每天买卖(因为没有交易手续费);
遇到价格下降的交易日,不买卖,因此永远不会亏钱。
赚到了所有交易日的钱,所有亏钱的交易日都未交易,理所当然会利益最大化。

1)所以我们第一种方法就是直接计算相邻两天的利润,如果大于0就进行累加。
2)第二种方法参照官网的介绍是:比较波峰波谷法实际上也是计算两天的差异,分别找到波谷进行买入,波峰进行卖出。稳稳的赚个差价

建议从第一种方法进行理解,之后可以参考第二种解法,你会发现豁然开朗!

主要代码python

利润和

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] - prices[i-1] > 0:
                profit += prices[i] - prices[i-1]
        return profit

波峰波谷

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<1:
            return 0
        index = 0
        low = up = prices[0]
        profit = 0
        while index < len(prices)-1:
            # 找波谷
            while index < len(prices) - 1 and prices[index]>=prices[index+1]:
                index = index + 1
            low = prices[index]
            # 找波峰
            while index < len(prices) - 1 and prices[index]<=prices[index+1]:
                index = index + 1
            up = prices[index]
            profit += up - low
        return profit

题目链接:https://leetcode-cn.com/problems/two-sum/solution/best-time-to-buy-and-sell-stock-ii

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值