Given an integer array nums, find asubarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Note that the product of an array with a single element is the value of that element.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104-10 <= nums[i] <= 10- The product of any subarray of
numsis guaranteed to fit in a 32-bit integer.
自己做就是不会,虽然其实挺直观的。
思路和53有点像,需要记录遍历到当前的最大值,以及最后的结果。但因为这题是乘法,可能会出现负负得正的情况,所以有可能负负得正以后反而成为了更大值,因此需要同时记录当前的最大和当前的最小。对于遍历到当前这个数字i,它这会儿的最大值就是max(numsi, numsi * currMax, numsi * currMin),以及需要更新currMax和currMin。
class Solution {
public int maxProduct(int[] nums) {
int currMin = nums[0];
int currMax = nums[0];
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
int newMin = Math.min(nums[i], Math.min(currMin * nums[i], currMax * nums[i]));
int newMax = Math.max(nums[i], Math.max(currMin * nums[i], currMax * nums[i]));
currMin = newMin;
currMax = newMax;
result = Math.max(result, currMax);
}
return result;
}
}
根据gpt老师,还可以简化成如果当前数字是负数,就交换最大值和最小值。我自己没写代码,太懒了,贴gpt老师的答案好了。
class Solution {
public int maxProduct(int[] nums) {
int maxProduct = 1;
int minProduct = 1;
int result = nums[0];
for (int x : nums) {
if (x < 0) {
int temp = maxProduct;
maxProduct = minProduct;
minProduct = temp;
}
maxProduct = Math.max(x, maxProduct * x);
minProduct = Math.min(x, minProduct * x);
result = Math.max(result, maxProduct);
}
return result;
}
}