zoukankan      html  css  js  c++  java
  • LeetCode 188. Best Time to Buy and Sell Stock IV (stock problem)

    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 at most k transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    分析

    依然是stock problem模型,但这次必须压缩空间,否则超限,并且在 k>prices.size() 时,转化为k=+无穷的情况,否则超限。

    const int inf=-999999;
    class Solution {
    public:
        int maxProfit(int k, vector<int>& prices) {
         if(prices.size()<=1) return 0;
         if (k >= prices.size()) {
            int T_ik0 = 0, T_ik1 =inf;
            for (auto price : prices) {
                T_ik1 = max(T_ik1, T_ik0 - price);
                T_ik0 = max(T_ik0, T_ik1 + price);
    
            }
            return T_ik0;
         }
            int sell[k+1]={0},buy[k+1];
            fill(buy,buy+k+1,inf);
            for(int i=0;i<prices.size();i++)
                for(int j=1;j<=k;j++){
                    sell[j]=max(sell[j],buy[j]+prices[i]);
                    buy[j]=max(buy[j],sell[j-1]-prices[i]);
                }
            return sell[k];
        }
    };
    
    
  • 相关阅读:
    对于git的认识
    第一篇博客
    结对编程
    对git的认识
    李叔同先生的《梦》
    51nod 1449 砝码称重
    LeetCode 21-29题解
    LeetCode 11-20题解
    LeetCode 6-10 题解
    LeetCode刷题重启博客
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10055821.html
Copyright © 2011-2022 走看看