zoukankan      html  css  js  c++  java
  • 188. Best Time to Buy and Sell Stock IV (Array; DP)

    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).

    思路:用状态存储至当前日为止第jth buy/sell的最大利润。到了第二天,我们可以按j从大到小(因为j大的新状态依赖于之前j小的状态),修改这个状态。

    class Solution {
    public:
        int maxProfit(int k, vector<int>& prices) {
            int dates = prices.size();
            if(dates <= 1 || k == 0) return 0;
            if (k >= prices.size()) return maxProfit2(prices); //unlimited transaction
            
            vector<int> release(k,0); //sell stock
            vector<int> hold(k,INT_MIN); //buy stock
            
            for(int i = 0; i < dates; i++){
                for(int j = k-1; j > 0; j--){
                    release[j] = max(release[j], hold[j]+prices[i]); //jth sell happen at ith day 
                    hold[j]=max(hold[j], release[j-1]-prices[i]); //jth buy happen at ith day
                }
                release[0] = max(release[0], hold[0]+prices[i]);
                hold[0] = max(hold[0],-prices[i]);
            }
            return release[k-1];
        }
        
        int maxProfit2(vector<int> &prices) {
            int profit = 0;
            for (int i=0; i<(int)prices.size()-1; i++) {
                if (prices[i+1] > prices[i])
                    profit += prices[i+1] - prices[i];
            }
            return profit;
        }
    };
  • 相关阅读:
    适配器模式
    控制器的显示注入
    自定义过滤器
    配置路由
    JavaScript判断浏览器类型及版本(新增IE11)
    路径别名
    判断是否是IE浏览器和是否是IE11
    页面视图中的按钮操作指向
    安卓开发环境搭建与环境变量设置
    html中iframe子页面与父页面元素的访问以及js变量的访问
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5050075.html
Copyright © 2011-2022 走看看