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];
        }
    };
    
  • 相关阅读:
    切换到真正的最高权限 SYSTEM 账户界面
    javascript中replace的正则表达式语法
    微软系统漏洞_超长文件路径打造私人地盘
    JAVA控制台
    PowerPoint绘图笔不能用
    《JavaScript核心技术》
    Catch(...) C++中三个点
    XMLHttp连续调用SEND需要注意的问题
    Wscript中的事件机制
    JavaScript(JS)常用的正则表达式
  • 原文地址:https://www.cnblogs.com/pk28/p/8635847.html
Copyright © 2011-2022 走看看