【LeetCode】【Solution】Maximum Product Subarray

来源:互联网 发布:淘宝模拟试衣服 编辑:程序博客网 时间:2024/05/16 16:05

【题目】

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.

【解法】

参考 http://segmentfault.com/blog/riodream/1190000000691766 

public class Solution {    public int maxProduct(int[] A) {        if (A.length == 0) return 0;        if (A.length == 1) return A[0];                int max_ending_here = 0;        int min_ending_here = 0;        int max_so_far = 0;                for (int i = 0; i < A.length; i++) {            if (A[i] > 0) {                max_ending_here = Math.max(max_ending_here * A[i], A[i]);                min_ending_here = Math.min(min_ending_here * A[i], A[i]);            } else if (A[i] == 0) {                max_ending_here = 0;                min_ending_here = 0;            } else {                int temp = max_ending_here;                max_ending_here = Math.max(min_ending_here*A[i], A[i]);                min_ending_here = Math.min(temp * A[i], A[i]);            }                        if (max_ending_here > max_so_far) {                max_so_far = max_ending_here;            }        }                return max_so_far;    }}

【标准Solution】

Let us denote that:

f(k) = Largest product subarray, from index 0 up to k.

Similarly,

g(k) = Smallest product subarray, from index 0 up to k.

Then,

f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )
上面就是动规方程

public int maxProduct(int[] A) {   assert A.length > 0;   int max = A[0], min = A[0], maxAns = A[0];   for (int i = 1; i < A.length; i++) {      int mx = max, mn = min;      max = Math.max(Math.max(A[i], mx * A[i]), mn * A[i]);      min = Math.min(Math.min(A[i], mx * A[i]), mn * A[i]);      maxAns = Math.max(max, maxAns);   }   return maxAns;}

【声明】本博客只是用于学习和交流,如不小心侵犯了您的权益,请联系本人,我会及时处理,谢谢!

0 0