zoukankan      html  css  js  c++  java
  • 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]
    

    思路:dp[i][0]代表第i天清仓能得到的最大值,dp[i][1]表示第i天持仓能得到的最大值。
    那么如果没有冷却期的话,dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]),dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]). 现在是有一天的冷却期,那么dp[i][1]=max(dp[i-1][1],dp[i-2][0]-prices[i]),即要保证今天持仓是由前天转移过来的。事实上前天dp[i-2][0]并不一定是清仓后的结果,也可能是根本没买,但(根本不买的这种情况)并不影响最后结果..

    class Solution {
    public:
        // 0
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if (n == 0) return 0;
            vector<vector<int> > dp(n, vector<int>(2));
            int ans = 0;
            for (int i = 0; i < n; ++i) {
                if (i == 0) {
                    dp[i][1] = -prices[i];
                    dp[i][0] = 0;
                } else {
                    //dp[i][1] = dp[i-1][1];
                    dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); 
                    if(i>=2) dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i]);
                    else dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]);
                }
            }
            return dp[n-1][0];
        }
    };
    
  • 相关阅读:
    【BZOJ 3754】: Tree之最小方差树
    【cogs 775】山海经 ——Segment Tree
    【BZOJ 3626】 [LNOI2014]LCA【在线+主席树+树剖】
    【BZOJ 2004】: [Hnoi2010]Bus 公交线路
    开启22端口
    将MySQL数据库表结构,自动生成PDM方法
    linux环境 创建多版本php
    mysql 数据类型选择浅谈
    int(5) 到底是多长
    (记)小程序如何发布
  • 原文地址:https://www.cnblogs.com/pk28/p/8635847.html
Copyright © 2011-2022 走看看