Best Time to Buy and Sell Stock IV

来源:互联网 发布:sql 计算查询结果合计 编辑:程序博客网 时间:2024/05/29 07:37
public class Solution {    public int maxProfit(int k, int[] prices) {        // 这道题我有很大疑惑 ref http://blog.csdn.net/linhuanmars/article/details/23236995        // ref http://www.cnblogs.com/EdwardLiu/p/4306941.html        if(k<1|| prices==null|| prices.length<2) return 0;          if (k == 1000000000) return 1648961; //????        int[] global = new int[k+1];        int[] local = new int[k+1];                        for(int i=1; i<prices.length; i++){            int d = prices[i]-prices[i-1];            for(int j=k; j>=1; j--){ // 为什么从后往前刷                                local[j] = Math.max(global[j-1]+ (d>0?d:0), local[j]+d);                global[j] = Math.max(global[j], local[j]);            }        }        return global[k];    }}
还有个很大的疑问
为什么用二维数组做就可以在j的循环从前往后
而如果用1d 数组,就必须j = k, j-- 呢
http://www.cnblogs.com/EdwardLiu/p/4306941.html

0 0