标签:
这几道题最好连着做, 模式就是loc 和global比,难点在于求出loc,咦,我做过这个梦吔
I 只能交易一次,那么loc就和0比 loc = max(loc+diff, 0)
为啥是loc+当天diff呢?比如 1,2,4, 1买进,2-1的差价在loc里存着,到了4 的时候4和1 的差价=4-2 + 2-1 = loc + p[i]-p[i-1]
public class Solution { public int maxProfit(List<Integer> prices) { if(prices==null||prices.size()==0) return 0; int len =prices.size(), loc=0, global = 0; for(int i=1;i<len;i++){ loc = Math.max(prices.get(i)-prices.get(i-1)+loc,0);// +loc 的意思是如果之前没卖掉,那么现在卖掉的获利 global = Math.max(loc,global); } return global; } } //http://blog.csdn.net/linhuanmars/article/details/23162793
II 能无限次交易,那loc就看今天买划算否, loc = Max(loc, loc + diff)
public class Solution { public int maxProfit(List<Integer> prices) { if(prices==null||prices.size()==0) return 0; int len = prices.size(); int loc=0, global = 0; for(int i=1;i<len;i++){ loc = Math.max(loc+prices.get(i)-prices.get(i-1), loc); global = Math.max(loc, global); } return global; } }
III at most two transactions
天题系列哟
Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4437114.html