1. Nested Loops Product Evaluation (Brute Force)
Intuition
Iterate over all possible starting positions i from 0 to n-1. For each i, expand j from i to n-1 maintaining the count of negative numbers and checking for zeros. If any element is 0, the product becomes 0. If the negative count is even (and positive count > 0), product is positive; update maxLen.
When to apply: Use to understand the sign multiplication rules before optimizing with dynamic programming.
All Subarrays Sign Tracking (O(N^2) Time)
2 of 2 questions left todaySingle positive element qualifies
Single positive element qualifies.
public class Main { public static class Solution { public int getMaxLen(int[] nums) { int n = nums.length; int maxLen = 0; for (int i = 0; i < n; i++) { int negCount = 0; for (int j = i; j < n; j++) { if (nums[j] == 0) break; if (nums[j] < 0) negCount++; if (negCount % 2 == 0) { maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, -2, -3, 4}; System.out.println("Max Length: " + sol.getMaxLen(nums)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Two nested loops checking all subarrays takes O(n2) iterations. - Space complexity:
O(1)— Only constant extra variables are needed.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.