zoukankan      html  css  js  c++  java
  • 188 Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV

    假设你有一个数组,其中第 i 个元素是第 i 天给定股票的价格。
    设计一个算法来找到最大的利润。您最多可以完成 k 笔交易。
    注意:
    你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    详见:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/

    Java实现:

    class Solution {
        public int maxProfit(int k, int[] prices) {
            int n=prices.length;
            if(n==0||prices==null){
                return 0;
            }
            if(k>=n){
                int res=0;
                for(int i=1;i<n;++i){
                    if(prices[i]-prices[i-1]>0){
                        res+=prices[i]-prices[i-1];
                    }
                }
                return res;
            }
            int[] g=new int[k+1];
            int[] l=new int[k+1];
            for(int i=0;i<n-1;++i){
                int diff=prices[i+1]-prices[i];
                for(int j=k;j>=1;--j){
                    l[j]=Math.max(g[j-1]+Math.max(diff,0),l[j]+diff);
                    g[j]=Math.max(g[j],l[j]);
                }
            }
            return g[k];
        }
    }
    

    C++实现:

    class Solution {
    public:
        int maxProfit(int k, vector<int> &prices) {
            if (prices.empty())
            {
                return 0;
            }
            if (k >= prices.size())
            {
                return solveMaxProfit(prices);
            }
            int g[k + 1] = {0};
            int l[k + 1] = {0};
            for (int i = 0; i < prices.size() - 1; ++i)
            {
                int diff = prices[i + 1] - prices[i];
                for (int j = k; j >= 1; --j)
                {
                    l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff);
                    g[j] = max(g[j], l[j]);
                }
            }
            return g[k];
        }
        int solveMaxProfit(vector<int> &prices)     {
            int res = 0;
            for (int i = 1; i < prices.size(); ++i) 
            {
                if (prices[i] - prices[i - 1] > 0) 
                {
                    res += prices[i] - prices[i - 1];
                }
            }
            return res;
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/4295761.html

  • 相关阅读:
    struts2+jpa+spring 泛型版小结
    PasswordEncoder
    父窗口 子窗口
    Powerdesigner的PDM(物理数据模型)生成数据库及逆向工程(将现有的数据库生成PDM)
    js 正则表达式
    <aop:config>
    CJDBC
    struts2取值
    mysql启动错误1067的解决
    杂碎
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8744775.html
Copyright © 2011-2022 走看看