Leetcode算法学习日志-309 Best Time to Buy and Sell Stock with Cooldown

Leetcode 309 Best Time to Buy and Sell Stock with Cooldown

题目原文

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like(ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

题意分析

买卖股票,每次买必须在上一次卖完一天(或大于一天)以后,求最大收益是多少。

解法分析

这种买卖股票问题是典型的动态规划问题,对于某一天的最大收益,分两种情况,一种是这天hold了一支股票,另一种是手里没有股票。可以得到递归式如下:

hold[i]=max(hold[i-1],non[i-2]-price),non[i]=max(non[i-1],hold[i-1]+price)。对于第i天的收益和前一天的收益,可以用同一个变量表示,再前一天的可以用另一个新的变量表示,本题需要注意初始值得选取。C++代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int preNon=0,non=0,hold=INT_MIN,temphold;
        for(auto price:prices){
            temphold=hold;//temphold is not necessary
            hold=max(hold,preNon-price);
            preNon=non;
            non=max(non,temphold+price);
        }
        return non;   
    }
};
preNon用来存储non[i-2],由于hold的值要么取hold,要么为preNon-price,当为preNon-price时,non一定取前一次的non,所以不影响non的新值,因此temphold不必要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值