LeetCode #309 Best Time to Buy and Sell Stock with Cooldown

Problem Description

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]

Some Details

  • 标准的简单DP题目

Solution

DP没怎么切,这题虽然难度不高但是既然切到了就赶快写了,毕竟作业难以完成= =。
买入,卖出,冷却,三状态,ok
f[i][0] 第i天手上没货的最优获利
f[i][1] 第i天手上有货的最优获利
f[i][2] 第i天进入冷却的最优获利
转移方程:
f[i][0]=max(f[i-1][0],f[i-1][2])
//前一天就没货或者前一天冷却
f[i][1]=max(f[i-1][0]-price[i],f[i-1][1])
//前一天就有货或者今天买入
f[i][2]=f[i-1][1]+price[i];
//前一天有货今天卖了
结束思密达。

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int f[10100][4],siz=prices.size();
        if (siz==0) return 0;
        f[0][0]=0;
        f[0][1]=prices[0]*-1;
        f[0][2]=0;
        for (int i=1;i<siz;i++)
        {
            f[i][0]=max(f[i-1][0],f[i-1][2]);
            f[i][1]=max(f[i-1][0]-prices[i],f[i-1][1]);
            f[i][2]=f[i-1][1]+prices[i];
        }
        int ans=f[siz-1][0];
        ans=max(ans,f[siz-1][1]);
        ans=max(ans,f[siz-1][2]);
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值