Article directory
LeetCode Brushing Notes-Dynamic Programming-day6
152. Product Maximum Subarray
1. Topic
Link to the original title: 152. Maximum product subarray
2. Problem-solving ideas
Algorithm: dynamic programming + rolling array optimization
- f[i] represents all the maximum products obtained from 0 to i and selected a[i]
- g[i] represents all the minimum products obtained from 0 to i and selected a[i]
Then there are several situations:
- 当a[i] >= 0时,f[i] = max(a[i], f[i - 1] * a[i])
- 当a[i] < 0时,f[i] = max(a[i], g[i - 1] * a[i])
- When a[i] >= 0, g[i] = min(a[i], g[i - 1] * a[i])
- 当a[i] < 0时,g[i] = min(a[i], f[i - 1] * a[i])
can be combined as:
a[i] >= 0
at that timef[i] = max(a[i], max(f[i-1] * a[i],g[i-1]*a[i]))
a[i]<0
at that timef[i] = max(a[i], max(g[i-1] * a[i],f[i-1]*a[i])
Space can be optimized with rolling arrays. See code for details.
3. Code
class Solution {
public:
int maxProduct(vector<int>& a) {
int f=a[0],g=a[0];
int res=a[0];
for(int i=1;i<a.size();i++){
int t=a[i],fa=f*t,ga=g*t;
f=max(t,max(fa,ga));
g=min(t,min(fa,ga));
res=max(res,f);
}
return res;
}
};
1567. Length of Longest Subarray with Positive Product
1. Topic
Original title link: 1567. Length of the longest subarray whose product is a positive number
2. Problem-solving ideas
Algorithms: Dynamic Programming
We can use two arrays f[i]
and g[i]
:
f[i]
Indicates the length of the longest subarray whose product ends with the subscript i and is a positive numberg[i]
Indicates the length of the longest subarray whose product ends with the subscript i being a negative number
Here we can get the recursive formula:
- If the current number is greater than 0, that is
nums[i]>0
, the previous product is multiplied by the current number, the positive and negative will not change, so:f[i]=f[i-1]+1
- If
g[i-1]
it is not equal to 0, add one. If g[i-1] itself is 0, the positive number here will not change
- If the current number is less than 0, that is
nums[i]<0
, multiplying the previous product by the current number will change the sign of the product, so:- At this time,
g[i]
it should be equalf[i-1]+1
, becausef[i-1]
the product of the included numbers is a positive number, and the multiplication by the current number is just a negative number. f[i]
Need to considerg[i-1]
the situation, if it is 0, it is still 0g[i-1]
here , otherwise , the negative number multiplied by the negative number is a positive numberf[i]
f[i]=g[i-1]+1
- At this time,
- If the current number is 0, that is
nums[i]==0
, willf[i]
,g[i]
assign a value of 0 - Each traversal maintains the maximum value:
res=max(res,f[i]);
3. Code
class Solution {
public:
int getMaxLen(vector<int>& nums) {
int f=0,g=0;
if(nums[0]>0) f=1;
else if(nums[0]<0) g=1;
int res=f;
for(int i=1;i<nums.size();i++){
if(nums[i]>0){
f++;
g=(g==0)?0:g+1;
}else if(nums[i]<0){
int t=f;
f=(g==0)?0:g+1;
g=t+1;
}else{
f=0,g=0;
}
res=max(res,f);
}
return res;
}
};