Subject description:
Given an array of integers nums
, to find a product of the maximum sequence of contiguous subsequence (which comprises at least a sequence number).
Example 1: Input: [2,3, 2,4] Output: 6 Explanation: subarray [2,3] maximum product 6. Example 2: Input: [-2,0, -1] Output: 0 Explanation: The results can not be 2, since the [-2, -1] is not subarray.
Analysis of ideas:
Tags: dynamic programming
to calculate a current maximum value to iterate, constantly updated
current imax is the maximum order, the current maximum value imax = max (imax * nums [ i], nums [i])
due to the presence of negative, it will result in maximum becomes the smallest, smallest becomes the largest. It is also necessary to maintain this minimum value imin, imin = min (imin * nums [i], nums [i])
When the negative appears imax and imin exchange before proceeding calculation
time complexity: O (n)
class Solution { public int maxProduct(int[] nums) { int max = Integer.MIN_VALUE, imax = 1, imin = 1; for(int i=0; i<nums.length; i++){ if(nums[i] < 0){ int tmp = imax; imax = imin; imin = tmp; } imax = Math.max(imax*nums[i], nums[i]); imin = Math.min(imin*nums[i], nums[i]); max = Math.max(max, imax); } return max; } }