标签:case nta cas iat style from ESS tar and
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Overall, we need to loop through the array, at each new element, there‘re 2 options:
u can either multiply the new element to the existing product,
or start a new product from current index (discard previous results)
in this process we need to maintain and update 2 values:
max: the maximum cumulative product UP TO current element starting from SOMEWHERE in the past
min: the minimum cumuliative product UP TO current element
(because when we see a negative number, the "candidate" for max should instead become the previous min product, because a bigger number multiplied by negative becomes smaller)
base case: max = min = res = nums[0], need max and min because max * (negative number) -> min
induction rule:
(1) multiply current element
-> max1 = max * nums[i], max2 = min * nums[i], min1 = min * nums[i], min2 = max * nums[i]
(2) not multiply current element
-> max3 = nums[i], min3 = nums[i]
max = max(max1, max2, max3), min = min(min1, min2, min3), res = max(res, max)
M1: time: O(n), space: O(1)
class Solution { public int maxProduct(int[] nums) { if(nums == null || nums.length == 0) { return 0; } int max = nums[0]; int min = nums[0]; int res = nums[0]; for(int i = 1; i < nums.length; i++) { int tmp = max; max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]); min = Math.min(Math.min(tmp * nums[i], min * nums[i]), nums[i]); res = Math.max(res, max); } return res; } }
152. Maximum Product Subarray - Medium
标签:case nta cas iat style from ESS tar and
原文地址:https://www.cnblogs.com/fatttcat/p/13662431.html