Maximum Product subarray maximum continuous product subset

Source: Internet
Author: User

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.

This requirement is to find a continuous sub-array with the maximum product in an unnecessary array.

For example, [2, 3,-2, 4], because there may be negative numbers, you can set two temporary variables mint and maxt. Mint stores the product that is multiplied by a negative number, and maxt stores the large product.

For example, 2*3 = 6. At this time, mint = maxt = 6. When-2 is encountered next time, mint = maxt =-12. At this time, the product-12 is less than-2, make maxt =-2. To avoid the number or negative number, mint should be kept unchanged. If a negative number is encountered next time, the product is larger than maxt, and then exchanges ......

Specific Code:

 1 public class Solution { 2     public int maxProduct(int[] A) { 3         int n = A.length; 4         int mint = 1; 5         int maxt = 1; 6          7         int maxvalue = A[0]; 8         for(int i =  0 ; i < n ; i++){ 9             if(A[i] == 0){10                 mint = 1;11                 maxt = 1;12                 if(maxvalue < 0)13                     maxvalue = 0;14             }else{15                 int curmax = maxt * A[i];16                 int curmin = mint * A[i];17                 18                 maxt = curmax > curmin ? curmax : curmin;19                 mint = curmax > curmin ? curmin : curmax;20                 21                 if(maxt < A[i])22                     maxt = A[i];23                     24                 if(mint > A[i])25                     mint = A[i];26                     27                 if(maxt > maxvalue)28                     maxvalue = maxt;29             }30         }31         32         return maxvalue;33         34     }35 }

 

Maximum Product subarray maximum continuous product subset

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.