[LeetCode] Maximum Product Subarray, leetcodesubarray

Source: Internet
Author: User

[LeetCode] Maximum Product Subarray, leetcodesubarray

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 problem is to find a subsequence in the array, and requires that the product of the number in this subsequence is the largest of all subsequences.

If efficiency and optimization are not considered, you can list the combinations of all subsequences, calculate their product, and obtain the maximum value. As follows:

int maxProduct(int A[], int n) {        int i = 0, j = 0,k=0;        int ans = 0;        int product = 0;        for (i = n; i > 0; i--){            for (j = 0; j <= n-i; j++){                for (k = j; k < i; k++){                    product += A[k];                }                if (product>ans){                    ans = product;                }                product = 0;            }        }        return ans;    }

However, the efficiency is very low. In another way, we can think of this question as "local optimization and global optimization" in one-dimensional dynamic planning ". Therefore, we need to maintain two variables: the maximum value and the minimum value of the Continuous Product of the current position.

The maximum and minimum values can be obtained from the following three conditions: the last curMax * A [I], the last curMin * A [I], and A [I. As follows:

int maxProduct(int A[], int n) {        int ans = A[0];        int curMin = A[0];        int curMax = A[0];        int cur = 1;        for (int i = 1; i < n; i++){            cur = curMax;            curMax = max(max(A[i],A[i]*curMax),A[i]*curMin);            curMin = min(min(A[i], A[i] * cur), A[i] * curMin);            ans = max(ans, curMax);        }        return ans;    }

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.