problem Ⅰ
152. Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray within the array 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.
A subarray is a contiguous subsequence of the array.
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.
solution
class Solution {
public:
int maxProduct(vector<int>& nums) {
int res = 1, maxs = INT_MIN;
for(auto i : nums){
res *= i;
if(res > maxs) maxs = res;
if(i == 0) res = 1;
}
res = 1;
for(int i=nums.size()-1; i>=0; i--){
res *= nums[i];
if(res > maxs) maxs = res;
if(nums[i] == 0) res = 1;
}
return maxs;
}
};
NOTE :
l didn’t come up with the solution of this problem at first, but now i got it.
let’s started with the problem without “zeros”
and then we can divide this problem into several situations
- without negative element
- we can directly return the product of all element
- with negative element
- even numbers
- we can directly return the product of all element
- odd numbers
- we have to remove an negative numbers
- even numbers
so how can we do it?
what we have to do is to remove the negative number at first / last, just like the illustration above, if we remove the mid, we got 1 and 2, if we remove the first or last, we get 3 and 4, it’s obviously that 3 and 4 is bigger than 1 and 2
and then we compare 3 and 4, choose the one bigger as answer
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
1
)
O(1)
O(1)
problem Ⅱ
1567. Maximum Length of Subarray With Positive Product
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
solution
class Solution {
public:
int getMaxLen(vector<int>& nums) {
int res = 1, lens=0, maxs = 0;
for(auto i : nums){
if(i == 0){
res = 1, lens = 0;
}else{
res *= (i < 0)?-1:1;
++lens;
if(res > 0 && lens > maxs) maxs = lens;
}
}
res = 1, lens = 0;
for(int i=nums.size()-1; i>=0; i--){
if(nums[i] == 0){
res = 1, lens = 0;
}else{
res *= (nums[i] < 0)?-1:1;
++lens;
if(res > 0 && lens > maxs) maxs = lens;
}
}
return maxs;
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
space complexity
:
O
(
1
)
O(1)
O(1)