Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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].
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Greedy
[1,-2,-3,4]
[0,1,-2,-3,-4]
[-1,-2,-3,0,1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1567: Maximum Length of Subarray With Positive Product
class Solution {
public int getMaxLen(int[] nums) {
int n = nums.length;
int[] f = new int[n];
int[] g = new int[n];
f[0] = nums[0] > 0 ? 1 : 0;
g[0] = nums[0] < 0 ? 1 : 0;
int ans = f[0];
for (int i = 1; i < n; ++i) {
if (nums[i] > 0) {
f[i] = f[i - 1] + 1;
g[i] = g[i - 1] > 0 ? g[i - 1] + 1 : 0;
} else if (nums[i] < 0) {
f[i] = g[i - 1] > 0 ? g[i - 1] + 1 : 0;
g[i] = f[i - 1] + 1;
}
ans = Math.max(ans, f[i]);
}
return ans;
}
}
// Accepted solution for LeetCode #1567: Maximum Length of Subarray With Positive Product
func getMaxLen(nums []int) int {
n := len(nums)
f := make([]int, n)
g := make([]int, n)
if nums[0] > 0 {
f[0] = 1
}
if nums[0] < 0 {
g[0] = 1
}
ans := f[0]
for i := 1; i < n; i++ {
if nums[i] > 0 {
f[i] = f[i-1] + 1
if g[i-1] > 0 {
g[i] = g[i-1] + 1
} else {
g[i] = 0
}
} else if nums[i] < 0 {
if g[i-1] > 0 {
f[i] = g[i-1] + 1
} else {
f[i] = 0
}
g[i] = f[i-1] + 1
}
ans = max(ans, f[i])
}
return ans
}
# Accepted solution for LeetCode #1567: Maximum Length of Subarray With Positive Product
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
f = [0] * n
g = [0] * n
f[0] = int(nums[0] > 0)
g[0] = int(nums[0] < 0)
ans = f[0]
for i in range(1, n):
if nums[i] > 0:
f[i] = f[i - 1] + 1
g[i] = 0 if g[i - 1] == 0 else g[i - 1] + 1
elif nums[i] < 0:
f[i] = 0 if g[i - 1] == 0 else g[i - 1] + 1
g[i] = f[i - 1] + 1
ans = max(ans, f[i])
return ans
// Accepted solution for LeetCode #1567: Maximum Length of Subarray With Positive Product
struct Solution;
impl Solution {
fn get_max_len(nums: Vec<i32>) -> i32 {
nums.split(|&x| x == 0)
.map(Self::max_length)
.max()
.unwrap_or(0)
}
fn max_length(v: &[i32]) -> i32 {
let mut neg = 0;
let mut res = 0;
let n = v.len();
let mut first_neg: Option<usize> = None;
for i in 0..n {
if v[i] < 0 {
neg += 1;
if first_neg.is_none() {
first_neg = Some(i);
}
}
if neg % 2 == 0 {
res = res.max((i + 1) as i32);
} else {
if let Some(j) = first_neg {
res = res.max((i - j) as i32);
}
}
}
res
}
}
#[test]
fn test() {
let nums = vec![1, -2, -3, 4];
let res = 4;
assert_eq!(Solution::get_max_len(nums), res);
let nums = vec![0, 1, -2, -3, -4];
let res = 3;
assert_eq!(Solution::get_max_len(nums), res);
let nums = vec![-1, -2, -3, 0, 1];
let res = 2;
assert_eq!(Solution::get_max_len(nums), res);
let nums = vec![-1, 2];
let res = 1;
assert_eq!(Solution::get_max_len(nums), res);
let nums = vec![1, 2, 3, 5, -6, 4, 0, 10];
let res = 4;
assert_eq!(Solution::get_max_len(nums), res);
}
// Accepted solution for LeetCode #1567: Maximum Length of Subarray With Positive Product
function getMaxLen(nums: number[]): number {
const n = nums.length;
const f: number[] = Array(n).fill(0);
const g: number[] = Array(n).fill(0);
if (nums[0] > 0) {
f[0] = 1;
}
if (nums[0] < 0) {
g[0] = 1;
}
let ans = f[0];
for (let i = 1; i < n; i++) {
if (nums[i] > 0) {
f[i] = f[i - 1] + 1;
g[i] = g[i - 1] > 0 ? g[i - 1] + 1 : 0;
} else if (nums[i] < 0) {
f[i] = g[i - 1] > 0 ? g[i - 1] + 1 : 0;
g[i] = f[i - 1] + 1;
}
ans = Math.max(ans, f[i]);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.