LeetCode-Best Time to Buy and Sell Stock III[dp]
Posted Little_Lu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于LeetCode-Best Time to Buy and Sell Stock III[dp]的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-Best Time to Buy and Sell Stock III[dp]
LeetCode-Best Time to Buy and Sell Stock I&&II
算法分析与设计第一周121.Best Time to Buy and Sell Stock&122. Best Time to Buy and Sell Stock II
Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II