leetcode 309. 最佳买卖股票时机含冷冻期

单次交易 121. 买卖股票的最佳时机

多次交易加手续费 714. 买卖股票的最佳时机含手续费

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

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

卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

 

题解:

1.一个代表股票价格的整数数组

2.进行多次交易(买入卖出),使最大利润

3.未卖出前不能买入

4.1天冷冻期:卖出股票后,无法第二天买入

 

示例:

输入: [1,2,3,0,2]

输出: 3 

解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

 

解题思路:

  • 记录一个上一次交易利润,为考虑所有情况,卖出后第二天用上一次利润去卖出比较,保留两次获得利润大的那个

C/C++题解:

class Solution {

public:

    int maxProfit(vector<int>& prices) {

        int maxProf=0, hold=INT_MIN;

        int PremaxProf=0;//记录上一个利润

        for(int i=0;i<prices.size();i++){

            int tmp = maxProf;//买入和不买入

            //以prices[i]价格卖出时,获得prices[i]的卖出金额,

            maxProf = max(maxProf,hold+prices[i]);

            //以prices[i]价格买入,考虑到冷却一天,从上一个利润中减去买入价格

            hold = max(hold,PremaxProf-prices[i]);

            PremaxProf = tmp;}

        return  maxProf;}};

Debug结果:

Java题解:

class Solution {

    public int maxProfit(int[] prices) {

        int maxProf=0, hold=Integer.MIN_VALUE;

        int PremaxProf=0;//记录上一个利润

        for(int i=0;i<prices.length;i++){

            int tmp = maxProf;//买入和不买入

            //以prices[i]价格卖出时,获得prices[i]的卖出金额,

            maxProf = Math.max(maxProf,hold+prices[i]);

            //以prices[i]价格买入,考虑到冷却一天,从上一个利润中减去买入价格

            hold = Math.max(hold,PremaxProf-prices[i]);

            PremaxProf = tmp; }

        return  maxProf;}}

Debug结果:

Python题解:

class Solution(object):

    def maxProfit(self, prices):

        """:type prices: List[int]:rtype: int"""

        maxProf, hold = 0, -sys.maxint

        PremaxProf=0 #记录上一个利润

        for i in range(len(prices)):

            tmp = maxProf #买入和不买入

            #以prices[i]价格卖出时,获得prices[i]的卖出金额,

            maxProf = max(maxProf,hold+prices[i])

            #以prices[i]价格买入,考虑到冷却一天,从上一个利润中减去买入价格

            hold = max(hold,PremaxProf-prices[i])

            PremaxProf = tmp

        return  maxProf

Debug结果:

更多题解移步公众号免费获取

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值