152. Maximum Product Subarray
作者:互联网
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官
找到数组中的子数组相乘最大的数字,数字中有负数。
动态规划,用两个数组,一个存到当前节点最大的结果,一个存到当前节点最小的结果。用一个变量存最终答案。方授权,非商业转载请注明出处。
class Solution {
public int maxProduct(int[] nums) {
int ans = nums[0];
int[] dpMax = new int[nums.length];
int[] dpMin = new int[nums.length];
dpMax[0] = ans;
dpMin[0] = ans;
for (int i = 1; i < nums.length; i++) {
dpMax[i] = Math.max(nums[i], Math.max(dpMax[i - 1] * nums[i], dpMin[i - 1] * nums[i]));
dpMin[i] = Math.min(nums[i], Math.min(dpMax[i - 1] * nums[i], dpMin[i - 1] * nums[i]));
ans = Math.max(dpMax[i], ans);
}
return ans;
}
}
粽子包子粿条 发布了126 篇原创文章 · 获赞 2 · 访问量 5223 私信 关注
标签:Product,152,nums,int,dpMin,dpMax,ans,Subarray,Math 来源: https://blog.csdn.net/lianggx3/article/details/104463662