天题系列:Best Time to Buy and Sell Stock III

public class Solution {
    public int maxProfit(List<Integer> prices) {
        // http://blog.csdn.net/linhuanmars/article/details/23236995
        if(prices==null||prices.size()<1) return 0;
        int len = prices.size();
        int[] global = new int[3] ;
        int[] loc = new int[3] ;
        for(int i=1;i<len;i++){ // 算每天都进行交易,进行完k次交易,的可能性
            int dif = prices.get(i)-prices.get(i-1);
            for(int j=2;j>0;j--){ //倒着进行是因为i的loop里顺序的把global和loc的值都排好了,所以要update的话需要用到i-1,j-1这样的数据,为了避免mess,从后update
                loc[j] = Math.max(global[j-1]+ (dif>0?dif:0), loc[j]+dif); // global可以加0 的缘故是,在最后一天买进,卖出,不做赔本生意了
                global[j] = Math.max(loc[j],global[j]);
            }
        }
        return global[2];
    }
}

ref 尤其是关于为啥第二层loop要倒着走的解释

http://blog.csdn.net/linhuanmars/article/details/23236995

posted @ 2015-04-18 12:42  世界到处都是小星星  阅读(224)  评论(0编辑  收藏  举报