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];
        }
    };
    
    
  • 相关阅读:
    C语言文件操作函数大全
    iOS
    HDU 5042 GCD pair 预处理+二分 分段
    swoole新手教程01-环境搭建及扩展安装
    Cocos2d-X中的Slider控件
    CSS之BFC
    代理server的概要知识
    C#比較对象的相等性
    Effective C++ 35,36,37
    oled屏幕
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10055821.html
Copyright © 2011-2022 走看看