#1567
Medium Algorithms Maximum length of subarray with positive product
Array Dynamic Programming Greedy
44.6% acceptance
Feb 25, 2026
2491
80
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 from that array.
Return the maximum length of a subarray with positive product.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn get_max_len(nums: Vec<i32>) -> i32 {
let mut pos = 0i32; // length of longest subarray ending here with positive product
let mut neg = 0i32; // length of longest subarray ending here with negative product
let mut ans = 0i32;
for &x in &nums {
if x > 0 {
pos = pos + 1;
neg = if neg > 0 { neg + 1 } else { 0 };
} else if x < 0 {
let new_pos = if neg > 0 { neg + 1 } else { 0 };
neg = pos + 1;
pos = new_pos;
} else {
pos = 0;
neg = 0;
}
ans = ans.max(pos);
}
ans
}
}