动态规划day06
1. 乘积最大子数组
题目描述:
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
思路:
实现代码:
class Solution {
public int maxProduct(int[] nums) {
int preMax = nums[0];
int preMin = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; ++i) {
int curMax = Math.max(nums[i], Math.max(preMax * nums[i], preMin * nums[i]));
int curMin = Math.min(nums[i], Math.min(preMax * nums[i], preMin * nums[i]));
max = Math.max(max, curMax);
preMax = curMax;
preMin = curMin;
}
return max;
}
}
2. 乘积为正数的最长子数组长度
题目描述:
给你一个整数数组 nums ,请你求出乘积为正数的最长子数组的长度。
一个数组的子数组是由原数组中零个或者更多个连续数字组成的数组。
请你返回乘积为正数的最长子数组长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-length-of-subarray-with-positive-product
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 1:
输入:nums = [1,-2,-3,4]
输出:4
解释:数组本身乘积就是正数,值为 24 。
示例 2:
输入:nums = [0,1,-2,-3,-4]
输出:3
解释:最长乘积为正数的子数组为 [1,-2,-3] ,乘积为 6 。
注意,我们不能把 0 也包括到子数组中,因为这样乘积为 0 ,不是正数。
示例 3:
输入:nums = [-1,-2,-3,0,1]
输出:2
解释:乘积为正数的最长子数组是 [-1,-2] 或者 [-2,-3] 。
示例 4:
输入:nums = [-1,2]
输出:1
示例 5:
输入:nums = [1,2,3,5,-6,4,0,10]
输出:4
提示:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
思路:
实现代码:
class Solution {
public int getMaxLen(int[] nums) {
if (nums.length == 1) return nums[0] > 0 ? 1 : 0;
//初始化
int positive = nums[0] > 0 ? 1 : 0;
int negative = nums[0] < 0 ? 1 : 0;
int maxLength = positive;
for (int i = 1; i < nums.length; ++i) {
if (nums[i] > 0) {//情况1
positive++;
negative = negative > 0 ? negative + 1 : 0;
} else if (nums[i] < 0) {//情况2
int temp = positive;
positive = negative > 0 ? negative + 1 : 0;
negative = temp + 1;
} else {//情况3
positive = 0;
negative = 0;
}
maxLength = Math.max(maxLength, positive);
}
return maxLength;
}
}