Leetcode--Maximum Product Subarray

Source: Internet
Author: User

Question:

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:

Finding a contiguous array in an array (the array contains at least one number) can produce the maximum product.

For example: given arrays [2, 3,-2, 4], the successive subarray is [2, 3], resulting in a maximum product of 6.

Analysis: The beginning of the problem will be wrong, thinking that the required sub-array can only be consecutive numbers and the reality is that as long as the following numbers than the current number can be regarded as a continuous array.

Therefore, the idea of dynamic programming can be adopted: the maximum product can be produced in two cases. (The key to solve this problem)

1) One of the largest numbers * a positive number

2) A minimum number * one negative

Therefore, we use two parameter max,min to record the maximum positive and the minimum negative number so far, respectively, Max and Min, and then use product to record the true maximum product. However, it is also important to note that one of the following occurrences is larger than the number of products currently accumulated, so the value of product should be updated to the value of the current array element, for example: [2,3,0,9] This case, 2*3 < 9, or vice versa.

Answer:

 Public classSolution { Public intMaxproduct (int[] nums) {       if(Nums = =NULL|| Nums.length = = 0)            return0; intmax = Nums[0]; intMin = nums[0]; intProduct = Nums[0];  for(intI=1; i<nums.length; i++) {            intA = nums[i] *Max; intb = nums[i] *min; Max=Math.max (Math.max (A, B), nums[i]); Min=Math.min (Math.min (A, B), nums[i]); Product=Math.max (max, product); }        returnproduct; }}

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