递推公式太难想了 并且为了省空间 这个答案只用了两个k大的数组 k代表交易次数
所以内层循环为何要从后往前进行就思考了很久 是为了不把上次外层循环算出的 j - 1覆盖掉 j 那一次还要用,所以不能从头上开始
具体local 和global的更新方式 看讲解
http://blog.csdn.net/linhuanmars/article/details/23236995
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int [] local = new int [ 3 ];
int [] global = new int [ 3 ];
for ( int i = 0; i < n - 1; i ++ ){
int diff = prices[ i + 1 ] - prices [ i ];
for ( int j = 2 ; j > 0; j -- ){
local [ j ] = Math.max( global[j - 1] + (diff > 0 ? diff : 0 ), local[ j ] + diff);
global [ j ] = Math.max ( local[ j ], global [ j ]);
}
}
return global [ 2 ];
}
}