Maximum product of sub-arrays [classic face question]

Source: Internet
Author: User

Topic

Given an integer array of length N, only the largest group in the combined product of the number of arbitrary (N-1) numbers can be computed by multiplication, not by division, and the time complexity of the algorithm is written out.

The idea of a poor lifting method

We find out the combination of all possible (N-1) numbers, calculate their product, and compare the size. Because there are a total of N (N-1) Number of combinations, the total time complexity is O (n^2), but obviously this is not the best idea.

idea two space change time

Computes the combined product of the number of (N-1), assuming that the element I (0<=i<=n-1) is excluded from the product (for example).

Set num[] as a preliminary array
Left[i] denotes the product of the first I element (including the first element) (0<=i<=n-1)
Left[i] = left[i-1] * Num[i]
Right[i] represents the product of the N-i element (including the first element) (0<=i<=n-1)
Right[i] = right[i+1] * Num[i]

Set P[i] The product of the other N-1 elements in an array other than the first element:
P[i] = left[i-1] * Right[i+1]

As an example:

P[4] = left[3] * Right[5]
= A1 * A2 * A3 * A4 * a6 * A7 * A8 * A9 * A10

Because the array left[] and right[] are only scanned two times from the head to the end, the linear time is p[i]. So it's easy to get the maximum value (just go through the p array once). The total time complexity is the time complexity of the computed array left[],right[],p[] plus the time complexity of finding the maximum value of p[] O (N).

Code One

  /* ---------------------------------------------* Date: 2015-02-15 * SJF0115 * Title: Maximum product of sub-array * Source: * Blog:-----------------------------------------------* *    #include <iostream>    #include <cstring>    using namespace STD;classSolution { Public:DoubleMaxproduct (DoubleNum[],intN) {if(N <=0){return 0; }//if            Doublemax = num[0],p;DoubleLeft[n],right[n];//Initializeleft[0] = num[0]; right[n-1] = num[n-1];//Calculate left array             for(inti =1; i < n;++i) {Left[i] = left[i-1] * Num[i]; }//for            //Calculate right array             for(inti = n2; I >=0;---) {Right[i] = right[i+1] * Num[i]; }//for            //Max            intLeft,right; for(inti =0; i < n;++i) {left = (I-1) >=0? left[i-1] :1; right = (i +1) < n? right[i+1] :1; p = left * right;if(P > Max)                {max = P; }//if}//for            returnMax }    };intMain () {solution solution;DoubleNum[] = {-2.5,-4,0.5,3,1,2,-3};cout<<solution. Maxproduct (NUM,7) <<endl; }

Two ideas

Through analysis, further reduce the amount of computation. Assuming that the product of n number is p, the positive and negative of P is analyzed as follows:
(1) p is 0
Then, the array contains at least one 0. Assuming that a 0 is removed, the product of the number of other N-1 is Q, which is discussed according to the positive and negative nature of Q:
Q is 0, indicating that there are at least two 0 in the array, then the product of the number of N-1 can only be 0.
Q is positive and returns Q. Because if you replace any of the remaining N-1 with 0, the resulting product is 0, less than the previous Q, so the product maximum is Q.
Q is negative and returns 0. Because if you replace any of the remaining N-1 with 0, the resulting knot product is 0, which is greater than the previous Q, so the product maximum value is 0.
(2) P is negative
According to the multiplicative nature of "negative negative positive", it is natural to think of removing a negative number from n integers, so that the product of N-1 is positive. To make this integer the largest, this removed negative value must be the smallest in the array. We just need to scan the array once, and remove the negative number from the absolute minimum.
(3) P is positive
In cases where P is negative, a positive value with the smallest absolute value should be removed so that the N-1 number product is the largest.

The above thinking uses a direct n number of product p, and then judge P positive and negative, but the direct product often has the risk of overflow, in fact, can do a small change, do not need a direct product, but the number of positive numbers in the group, negative and 0, so as to determine the positive and negative p.

In terms of time complexity, since only one traversal of an array is required, the number of positive, negative, and 0 in the array can be obtained while iterating through the array, as well as the smallest positive and negative values in the array, with the time Complexity O (N)

Code two

    /* ---------------------------------------------* Date: 2015-02-15 * SJF0115 * Title: Maximum product of sub-array * Source: * Blog:-----------------------------------------------* *    #include <iostream>    #include <climits>    #include <cmath>    using namespace STD;classSolution { Public:DoubleMaxproduct (DoubleNum[],intN) {if(N <=0){return 0; }//if            //absolute minimum negative number, absolute value minimum positive number            DoublePMin = Int_max,nmin = Int_max;//absolute minimum negative number, absolute value minimum positive number, 0 subscript            intPindex =0, NIndex =0, Zeroindex;//0, positive, negative number            intZcount =0, Pcount =0, ncount =0;//Remove the subscript from the element            intindex =0;//Statistics             for(inti =0; i < n;++i) {if(Num[i] = =0) {zeroindex = i;                ++zcount; }//if                Else if(Num[i] >0) {++pcount;//Absolute number of the smallest positive number                    if(Num[i] < pMin)                        {pindex = i;                    PMin = Num[i]; }//if}//else                Else{++ncount;//absolute minimum negative number                    if(fabs(Num[i]) < nMin) {nMin =fabs(Num[i]);                    NIndex = i; }//if}//else}//for            //p is 0            if(Zcount >0){//q is 0                if(Zcount-1>0){return 0; }//if                //q is negative                if(ncount%2){return 0; }//if                //q is positive                Else{//To fall off the element labeled Zeroindexindex = Zeroindex; }//else}//if            //P is the positive minus of the absolute minimum.            Else if(ncount%2==0) {index = Pindex; }//P is negative minus the absolute minimum negative            Else{index = NIndex; }//else            //Maximum product            DoubleMax =1; for(inti =0; i < n;++i) {if(I! = index)                {max *= num[i]; }//if}//for            returnMax }    };intMain () {solution solution;DoubleNum[] = {2.5,4,-0.5,3,-1,2,3};cout<<solution. Maxproduct (NUM,7) <<endl; }

Maximum product of sub-arrays [classic face question]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.