DP leetcode-Maximum Product subarray

Source: Internet
Author: User

I have been busy writing paper recently. I haven't done any questions for a long time, and I have complicated my questions .. The logic is very simple. You only need to update two values at a time: the maximum product of the current subsequence and the Minimum Product of the current subsequence. There are three possibilities for updating the Maximum Product: current A [I]> 0, multiplied by the previous maximum number (> 0) to obtain the new maximum product; current A [I] <0, multiply the first smallest number (<0) to obtain the new maximum product; a [I] It itself> 0, (a [I-1] = 0. The same is true for the minimum product ..


class Solution {public:int Max(int a, int b, int c){int max = -1 << 30;if (a >= b)max = a;elsemax = b;if (c > max)max = c;return max;}int Min(int a, int b, int c){int min = 1 << 30;if (a <= b)min = a;elsemin = b;if (c < min)min = c;return min;}int maxProduct(int A[], int n) {int maxPPrev=A[0], maxP;int minPPrev = A[0], minP;int max = A[0];for (int i = 1; i < n; i++){maxP = Max(maxPPrev * A[i], minPPrev * A[i], A[i]);minP = Min(maxPPrev * A[i], minPPrev * A[i], A[i]);maxPPrev = maxP;minPPrev = minP;if (maxPPrev > max)max = maxPPrev;if (minPPrev > max)max = minPPrev;}return max;}};


DP leetcode-Maximum Product subarray

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.