leetcode day7 买卖股票的最佳时机 III(有疑问

leetcode day7 买卖股票的最佳时机 III

问题描述

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

思路

最多可以完成 两笔 交易。
我们首先想通过贪心解决这个问题。但是这个问题不行,因为有最多两比交易的限制。
参看了前人的博客:
在这里插入图片描述

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0

        len_prices = len(prices)
        buy1, sell1, buy2, sell2 = -prices[0], 0, 0, 0

        for i in range(1, len_prices):
            buy1 = max(buy1, -prices[i])
            sell1 = max(sell1, buy1 + prices[i])
            buy2 = max(buy2, sell1 - prices[i])
            sell2 = max(sell2, buy2 + prices[i])

        return max(0, sell1, sell2)

我的错误代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    int max=0;
    int count=0;
    n=price.size();
        for(int i=0;i<n;i++){
            if(prices[i]>prices[i-1]){
                if(count=<2){
                    max=max+prices[i]-prices[i-1];
                    count++;
                }
            }
        }
        return max;
    }
};
``
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值