Leetcode 152:maximum Product Subarray

Source: Internet
Author: User

Maximum Product SubarrayTotal Accepted: 16617 Total Submissions: 96901

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 .

Analysis

Besides keeping track of the largest product, we also need to keep track of the smallest product.

Records the current maximum, minimum value. Because a negative number is encountered, the product with the minimum value may become the maximum value.

[Precautions]
Note the handling of the 0 value.

[CODE]


public class Solution {public    int maxproduct (int[] A) {        if (A==null | | A.LENGTH<1) return 0;        if (A.length < 2) return a[0];        int global = a[0];        int max = A[0], min = a[0];        for (int i=1; i<a.length; i++) {            int A = max*a[i];            int b = Min*a[i];                        max = Math.max (A[i], Math.max (A, b));            min = Math.min (A[i], math.min (A, b));            Global = Math.max (max, Global);        }                return global;    }}



Leetcode 152: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.