码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Best Time to Buy and Sell Stock III[dp]

时间:2017-07-11 11:10:04      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:algo   not   sign   public   return   min   for   tip   tran   

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;
    }
}

 

LeetCode-Best Time to Buy and Sell Stock III[dp]

标签:algo   not   sign   public   return   min   for   tip   tran   

原文地址:http://www.cnblogs.com/xiaolu266/p/7149269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!