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;
        }
    }
  • 相关阅读:
    向量的内积和外积
    软件姿态解算
    PLC与外接按钮开关接线方法图解
    关于三极管处于临界饱和状态的分析
    C语言中的volatile——让我保持原样
    C语言异或运算在程序设计中的妙用
    各种转PDF
    javax.mail发送邮件功能
    MySQL总结
    idea永久破解
  • 原文地址:https://www.cnblogs.com/xiaolu266/p/7149269.html
Copyright © 2011-2022 走看看