解法1:贪心
要计算买卖两次的收益,只需要找到一天k,使得f(0, k) + f(k + 1, n - 1)最大即可;
运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
case通过率为0.00%
public int maxProfit (int[] prices) {
// write code here
if(prices==null || prices.length==0){
return 0;
}
int max=Integer.MIN_VALUE;
for(int i=0;i<prices.length;i++){
int temp=getMax(prices,0,i)+getMax(prices,i+1,prices.length-1);
max=Math.max(max,temp);
}
return max;
}
public int getMax (int[] prices,int left,int right) {
int max=Integer.MIN_VALUE;
int min=Integer.MAX_VALUE;
for(int i=left;i<right;i++){
min=Math.min(min,prices[i]);
max=Math.max(max,prices[i]-min);
}
return max;
}解法2:一次循环
public int maxProfit (int[] prices) {
// write code here
if(prices.length==0){
return 0;
}
int firstbuy=prices[0],secondbuy=prices[0];
int profit1=0,profit2=0;
for(int i=0;i<prices.length;i++){
firstbuy=Math.min(firstbuy,prices[i]);
profit1=Math.max(profit1,prices[i]-firstbuy);
//为什么第二次价格是这样选
secondbuy=Math.min(secondbuy,prices[i]-profit1);
profit2=Math.max(profit2,prices[i]-secondbuy);
}
return profit2;
}解法3:正反两次循环
首先从后往前遍历数组,f[i]表示从i点开始到结尾 进行的一次交易的最大收益。
第二次交易处理完了,就可以用常见的方法进行类似一次交易,每次比较时再加上对应的f[i+1]即可。
res = Math.max(res,prices[i]-min + f[i+1]);
最后需要注意一点,并没有要求一定要进行两次交易。
public int maxProfit (int[] prices) {
// write code here
int n = prices.length;
if(n<2)
return 0;
//从后往前遍历,f[i] 表示从i点到之后的一次交易的最大收益
int[] f = new int[n];
int max = prices[n-1];
f[n-1] = 0; //初始化
for(int i=n-2;i>=0;i--){
max = Math.max(max,prices[i]);
f[i] = Math.max(f[i+1], max-prices[i]);
}
int res = 0;
//从前往后遍历
int min = Integer.MAX_VALUE;
for(int i=0;i<n-1;i++){
min = Math.min(min,prices[i]);
res = Math.max(res,prices[i]-min + f[i+1]);
}
return res;
}
京公网安备 11010502036488号