用动态规划的方法,就是要找到其转移方程式,也叫动态规划的递推式,动态规划的解法无非是维护两个变量,局部最优和全局最优。其中局部最优的意思就是到目前这个数字为止,其最好的值,整体最优就是整体的最好值。
例子:
Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
Product Subarray,要考虑到一种特殊情况,即负数和负数相乘:如果前面得到一个较小的负数,和后面一个较大的负数相乘,得到的反而是一个较大的数,如{2,-3,-7},所以,我们在处理乘法的时候,除了需要维护一个局部最大值,同时还要维护一个局部最小值,由此,可以写出如下的转移方程式:
max_copy[i] = max_local[i]
max_local[i + 1] = Max(Max(max_local[i] * A[i], A[i]), min_local * A[i])
min_local[i + 1] = Min(Min(max_local[i] * A[i], A[i]), min_local * A[i])
public class Solution {
public int maxProduct(int[] A) {
if(A.length<=0) return 0;
if(A.length==1) return A[0];
int curMax = A[0];
int curMin = A[0];
int ans = A[0];
for(int i=1;i<A.length;i++){
int temp = curMin *A[i];
curMin = Math.min(A[i], Math.min(temp, curMax*A[i]));
curMax = Math.max(A[i], Math.max(temp, curMax*A[i]));
ans = Math.max(ans, curMax);
}
return ans;
}
}