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