zoukankan      html  css  js  c++  java
  • LeetCode-Best Time to Buy and Sell Stock III[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 two transactions.

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

    标签: Array Dynamic Programming

    分析:动态规划,设left[i]表示0-i天的最大利润,right[j]表示j-n-1天的最大利润,所以状态方程为:

    left[i]=max(left[i-1],prices[i]-minleft);  minleft表示0-i天的最低价

    right[j]=max(right[j+1],maxright-prices[j]);  maxright表示j-n-1天的最高价;

    由于只可以买卖两次,并且在第二次买进是必须把第一次的卖掉,所以最大利润为max(left[i]+right[i]);

    参考代码:

    public class Solution {
        public int maxProfit(int[] prices) {
            int len=prices.length;
            if(len<2)
                return 0;
            int left[]=new int[len];
            int right[]=new int[len];
            int minleft=prices[0];
            left[0]=0;
            for(int i=1;i<len;i++){
                minleft=Math.min(minleft, prices[i]);
                left[i]=Math.max(left[i-1], prices[i]-minleft);
            }
            int maxright=prices[len-1];
            right[len-1]=0;
            for(int j=len-2;j>=0;j--){
                maxright=Math.max(maxright, prices[j]);
                right[j]=Math.max(right[j+1], maxright-prices[j]);
            }
            int maxProfit=left[0]+right[0];
            for(int i=0;i<len;i++){
                maxProfit=Math.max(maxProfit, left[i]+right[i]);
            }
            return maxProfit;
        }
    }
  • 相关阅读:
    matlab cell
    matlab linux 快捷键设置——有问题还是要解决
    latex 小结
    TOJ 1258 Very Simple Counting
    TOJ 2888 Pearls
    HDU 1248 寒冰王座
    TOJ 3486 Divisibility
    TOJ 3635 过山车
    TOJ 1840 Jack Straws
    HDU 4460 Friend Chains
  • 原文地址:https://www.cnblogs.com/xiaolu266/p/7149269.html
Copyright © 2011-2022 走看看