Maximum Product Subarray-leetcode

Source: Internet
Author: User

Find the contiguous subarray within an array (containing at least one number) which have the largest product.

For example, given the array [2,3,-2,4] ,
The contiguous Subarray has the [2,3] largest product = 6 .

Idea: DP. Here we don't actually need O (n) space, just record the maximum value that the variable will traverse to.

Where, because the product of the number, it is possible that the original two are negative values multiplied will become the largest product.

Therefore, we need to maintain two variables, maxpre and Minpre.

Maxpre the last digit is the maximum product of the interval of the previous position in the current location.

Minpre the last digit is the smallest product of the interval before the current position.

Then, taking into account the current position, there are:

Maxsofar = Max (max (Maxpre * nums[i], Minpre * nums[i]), nums[i]);

Minsofar = min (min (minpre * nums[i], Maxpre * nums[i]), nums[i]);

The maxresfound is then used to record the maximum value of the Maxsofar during the iteration, which is the result.

1 classSolution {2  Public:3     intMaxproduct (vector<int>&nums) {4         intn =nums.size ();5         if(n = =0)return 0;6         intMaxsofar, Minsofar, Maxresfound, Maxpre, Minpre;7Maxpre = Minpre = Maxsofar = Minsofar = Maxresfound = nums[0];8          for(inti =1; I < n; i++)9         {TenMaxsofar = Max (max (Maxpre * nums[i), Minpre *nums[i]), nums[i]); OneMinsofar = min (min (minpre * nums[i), Maxpre *nums[i]), nums[i]); AMaxresfound =Max (Maxresfound, Maxsofar); -Maxpre =Maxsofar; -Minpre =Minsofar; the         } -         returnMaxresfound; -     } -};

Maximum Product Subarray-leetcode

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.