LeetCode ---- Maximum Product Subarray

Source: Internet
Author: User

LeetCode ---- Maximum Product Subarray

Maximum Product Subarray

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.

Analysis:

Besides keeping track of the largest product, we also need to keep track of the smallest product. Why? The smallest product, which is the largest in the negative sense cocould become the maximum when being multiplied by a negative number.

Let us denote that:

f(k) = Largest product subarray, from index 0 up to k.

Similarly,

g(k) = Smallest product subarray, from index 0 up to k.

Then,

f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )

There we have a dynamic programming formula. using two arrays of sizen, we coshould deduce the final answer as f (n-1 ). since we only need to access its previous elements at each step, two variables are sufficient.

Code:
class Solution(object):    def maxProduct(self, nums):        """        :type nums: List[int]        :rtype: int        """        n = len(nums)        minP = [0] * n        maxP = [0] * n        minP[0] = nums[0]        maxP[0] = nums[0]        for i in range(1, n):            maxP[i] = max(nums[i], minP[i - 1]*nums[i], maxP[i - 1]*nums[i])            minP[i] = min(nums[i], minP[i - 1]*nums[i], maxP[i - 1]*nums[i])        return max(maxP)

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.