The beauty of programming----The maximum product of a sub-array

Source: Internet
Author: User

Problem: Given an integer array of length N, only multiplication is allowed, no division is used to calculate the maximum number of products in any combination of N-1, and the time complexity of the algorithm is written out.

Solution One: Use an array to save the product of the first element from the left to the right. Saves the product of n-i elements from right to left with another array. Then the result is the product of the elements in the two arrays, and the complexity is O (N).

Solution Two: Set n the product of the number of P, p analysis.

1,p is 0, the array contains at least one 0, assuming that after removing a 0, the product of the other N-1 number is q, if q is 0, then the array has at least two 0, then return 0. If q is positive, return Q. If q is negative, return 0.

2,p is negative. Scan the array once, removing the negative value of the absolute minimum.

3,p is a positive number. If there is a positive value in the array, the smallest positive value is removed, or the absolute maximum negative value is removed.

For P positive and negative judgement, can not be directly to the product, but scan the array, the number of positive numbers in the group, negative, and 0, so as to determine the positive and negative value of P, traverse the same time to find the absolute minimum of positive and negative, absolute value of the largest positive and negative, the complexity of O (N).

The beauty of programming----The maximum product of a sub-array

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.