题目:
最佳时间买入卖出股票:你有一个数组保存了股票在第i天的价钱,现在你最多进行两次买卖,但同一时间你手上只能保持一个股票,如何赚的最多
尝试一:
思路是将整个数组分成两部分,然后分别算两边买卖一次的最大盈利加起来得到当前分法的最大盈利。然后用一个loop遍历所有把数组砍成两截的方法得到最终的最大盈利。这样的话由于是嵌套的两个for循环,外层for循环中每一次执行都会把所有值检查一遍,复杂度为O(n^2).
public class Solution { public static int maxProfit(int[] prices) { if(prices.length==0) return 0; int min=prices[0]; int max=prices[prices.length-1]; int maxprofit=0; for (int i=0; i<prices.length;i++) { int profit_1=0; int profit_2=0; for(int j=1; j<=i; j++) {//计算左边最大盈利 if(prices[j]<min) min=prices[j]; int tem = prices[j]-min; if(tem>profit_1) profit_1=tem; } for(int j=prices.length-1; j>i; j--) {//计算右边最大盈利 if(prices[j]>max) max=prices[j]; int tem=max-prices[j]; if(tem>profit_2) profit_2=tem; } maxprofit=Math.max(maxprofit, profit_1+profit_2);//当前分法的最大总盈利值 } return maxprofit; } }
尝试二:
参考了http://blog.csdn.net/fightforyourdream/article/details/14503469
把之前里面分别计算左右最大盈利的for循环拿出来,先分别计算每种分法对应的左右最大盈利存到两个数组里。最后再用一个for循环得到总的最大盈利。这样由于每个循环的复杂度都是O(n),总的复杂度仍然是O(n).
public class Solution { public static int maxProfit(int[] prices) { if(prices.length<2) return 0; int min=prices[0]; int max=prices[prices.length-1]; int maxprofit=0; int [] left = new int[prices.length];//存放左边的最大盈利 int [] right = new int[prices.length];//存放右边的最大盈利 left[0] = 0; right[prices.length-1] = 0; for (int i = 1; i < prices.length; i++) { left[i] = Math.max(left[i-1], prices[i] - min);//计算[1,i]买卖一次的最大盈利 min = Math.min(min, prices[i]); } for (int i = prices.length-2; i>=0; i--) { right[i] = Math.max(right[i+1], max - prices[i]);//计算[i, prices.length-2]买卖一次的最大盈利 max = Math.max(max, prices[i]); } for (int i=0; i<prices.length;i++) { maxprofit=Math.max(maxprofit, left[i]+right[i]);//计算最大总盈利 } return maxprofit; } }
【leetcode】 Best Time to Buy and Sell Stock III,布布扣,bubuko.com
【leetcode】 Best Time to Buy and Sell Stock III
原文:http://blog.csdn.net/he_wolf/article/details/21319407