Best Time to Buy and Sell Stock III
首先想得的思路便是遍历
遍历数组,将数组分成左右2部分,分布对左右部分进行一次买卖,profit = leftProfit + rightProfit。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0){return 0;}
int maxProfit = getMaxProfitByOneStep(prices);
for(int i = 1;i<prices.length-1;i++)
{
int profit = getMaxProfitByOneStep(Arrays.copyOfRange(prices, 0, i+1))
+getMaxProfitByOneStep(Arrays.copyOfRange(prices, i+1, prices.length));
if(profit > maxProfit) maxProfit = profit;
}
return maxProfit;
}
int getMaxProfitByOneStep(int[] prices)
{
int maxProfit = 0;
int n = prices.length;
int price = prices[n-1];
for(int i = n-2;i>=0;i--)
{
int profit = price - prices[i];
if(prices[i] > price)
{
price = prices[i];
}
maxProfit = maxProfit > profit ? maxProfit : profit;
}
return maxProfit;
}
}
然而运行超时!
发现一些小规律。
1、如“1,2,3,4,5,3”递增,显然没必要从1到5都要split,然后求profit。直接在5处划分
2、如“2,5,4,3,2,1,4”递减,直接在1处划分,因为{“2,5,4,3,2”,“1,4”}={“2,5,4,3”,“2,1,4”}={“2,5,4”,“3,2,1,4”}={“2,5”,“4,3,2,1,4”}
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0){return 0;}
int maxProfit = getMaxProfitByOneStep(prices);
int right_begin = 0;
int left_end = 0;
for(int i = 1;i<prices.length-1;i++)
{
while(i<prices.length-2&&prices[i+1]>=prices[i]){i++;left_end = i;}
while(i<prices.length-2&&prices[i+1]<prices[i]){i++;right_begin = i; }
if(left_end<i){left_end = i;}
if(right_begin<i){right_begin=i+1;}
int profit = getMaxProfitByOneStep(Arrays.copyOfRange(prices, 0, left_end+1))
+getMaxProfitByOneStep(Arrays.copyOfRange(prices, right_begin, prices.length));
if(profit > maxProfit) maxProfit = profit;
}
return maxProfit;
}
int getMaxProfitByOneStep(int[] prices)
{
int maxProfit = 0;
int n = prices.length;
int price = prices[n-1];
for(int i = n-2;i>=0;i--)
{
int profit = price - prices[i];
if(prices[i] > price)
{
price = prices[i];
}
maxProfit = maxProfit > profit ? maxProfit : profit;
}
return maxProfit;
}
}
接下来自然而然想到动态规划!!
maxProfit = max{leftProfit[i]+rightProfit[j]};
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[] leftProfit = new int[n];
int[] rightProfit = new int[n];
int min = Integer.MAX_VALUE;
int maxProfit = 0;
for(int i = 0;i<n;i++)
{
min = Math.min(min, prices[i]);
maxProfit = Math.max(maxProfit, prices[i]-min);
leftProfit[i] = maxProfit;
}
int max = Integer.MIN_VALUE;
maxProfit = 0;
for(int i = n-1;i>=0;i--)
{
max = Math.max(max, prices[i]);
maxProfit = Math.max(maxProfit, max - prices[i]);
rightProfit[i] = maxProfit;
}
maxProfit = 0;
for(int i = 0 ;i<n;i++)
{
maxProfit = Math.max(maxProfit, leftProfit[i]+rightProfit[i]);
}
return maxProfit;
}
}