Maximum Product Subarray

来源:互联网 发布:单片机多线程 编辑:程序博客网 时间:2024/06/16 23:25

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.


class Solution {public:    int maxProduct(int A[], int n) {        int i,a,b,localmax,localmin,max;        if(n==0) return 0;        if(n==1) return A[0];        localmax=localmin=max=A[0];        for(i=1;i<n;i++){            a=localmax*A[i]>localmin*A[i]?localmax*A[i]:localmin*A[i];            b=localmax*A[i]<localmin*A[i]?localmax*A[i]:localmin*A[i];            localmax=a>A[i]?a:A[i];            localmin=b<A[i]?b:A[i];            max=max>localmax?max:localmax;        }        return max;    }};


0 0