[leetcode]152. Maximum Product Subarray Maximum product sub-array

Source: Internet
Author: User

Given an integer array nums , find the contiguous subarray within a array (containing at least one number) which have the Largest product.

Example 1:

Input: [2,3,-2,46Explanation: [2,3] has the largest product 6.

Example 2:

Input: [ -2,0,-102, because [ -2,-1] is not a subarray.

Test instructions

To find the maximum product sub-array

Ideas:

Negative negative positive, negative minus.

/Maximum product sub-array * nums[i]

So the nums[i] end of the maximum product sub-array depends on the end of Nums[i-1]

\ Minimum product sub-array * nums[i]

Code:

1 classSolution {2       Public intMaxproduct (int[] nums) {3         int[] max =New int[nums.length];4         int[] min =New int[nums.length];5Max[0] = nums[0];6Min[0] = nums[0];7         intresult = Nums[0];8          for(inti = 1; i < nums.length; i++){9Max[i] = Math.max (Math.max (max[i-1] * nums[i], min[i-1]*nums[i]), nums[i]);TenMin[i] = Math.min (Math.min (max[i-1] * nums[i], min[i-1]*nums[i]), nums[i]); Oneresult =Math.max (result, max[i]); A         } -         returnresult; -     } the}

[leetcode]152. Maximum Product Subarray Maximum product 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.