152. 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.

一维DP问题,由于算最大积,可能的情况是前一个最大正值乘以当前值或是前一个最小负值乘以最大值,因此需要记录最大及最小值:

DPmax[i] = max(DPmin[i-1]*n, DPmax[i-1]*n, n);

DPmin[i] = min(DPmin[i-1]*n, DPmax[i-1]*n, n);

max = max(DPmax[i], max);

由于只和前一个相关,使用滚动数组。

public class Solution {
  public int maxProduct(int[] A) {
    int max = 1;
    int min = 1;
    int ret = Integer.MIN_VALUE;
    for (int n : A) {
      int a = n * max;
      int b = n * min;
      max = Math.max(Math.max(a, b), n);
      min = Math.min(Math.min(a, b), n);
      ret = Math.max(ret, max);
    }
    return ret;
  }
}

posted on 2015-04-15 02:22  shini  阅读(104)  评论(0编辑  收藏  举报

导航