Leetcode: Maximum Product subarray

Source: Internet
Author: User

Description:

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


Idea: traverse the array from left to right, record the maximum and minimum values of the Child array product ending with the element currently traversed (because there may be negative numbers in the array ), at the same time, the maximum value of all obtained values is recorded. At the end of the loop, the maximum value of all obtained values is the expected value.


Code:

int Solution::maxProduct(int A[],int n){    if(n == 1)        return A[0];    int max_temp = A[0];    int min_temp = A[0];    int result = A[0];    int i;    for(i = 1;i < n;i++)    {        int max_temp2 = max_temp * A[i];        int min_temp2 = min_temp * A[i];        max_temp = max(max_temp2,max(min_temp2,A[i]));        min_temp = min(min_temp2,min(max_temp2,A[i]));        if(max_temp > result)            result = max_temp;    }    return result;}


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.