Leetcode-Maximum Product subarray ZZ

Source: Internet
Author: User
LinkedIn FAQ-maximum sum/product subarray

Maximum Sum subarray is the original question of leetcode, which is almost identical to the idea of gas station. The conclusions used in the answers must be proved in mathematics.

123456789101112 public int maxSubArray(int[] A) {    int sum = 0;    int max = Integer.MIN_VALUE;    for (int i = 0; i < A.length; i++) {        sum += A[i];        if (sum > max)            max = sum;        if (sum < 0)            sum = 0;    }    return max;}

Maximum Product subarray actually only needs to constantly record two values, Max and Min. Max is the largest positive product so far, Min is the smallest negative product so far, or 1.

123456789101112131415161718192021 public int maxProduct(int[] A) {    int x = 1;    int max = 1;    int min = 1;    for (int i = 0; i < A.length; i++) {        if (A[i] == 0) {            max = 1;            min = 1;        } else if (A[i] > 0) {            max = max * A[i];            min = Math.min(min * A[i], 1);        } else {            int temp = max;            max = Math.max(min * A[i], 1);            min = temp * A[i];        }        if (max > x)            x = max;    }    return x;}

 

Http://shepherdyuan.wordpress.com/2014/07/23/linkedin-maximum-sumproduct-subarray/

Leetcode-Maximum Product subarray ZZ

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.