1. Nested Loops All Subarrays
Intuition
Compute the product of every possible subarray (i..j) and record the maximum product.
Algorithm
- 1. Initialize maxProd = nums[0].
- 2. For i from 0 to n-1: - currentProd = 1 - For j from i to n-1: - currentProd *= nums[j] - maxProd = max(maxProd, currentProd).
- 3. Return maxProd.
Brute Force All Subarrays Product Scan
2 of 2 questions left todayPhase 1 — maxProd = 2: Step 1: Fix start index i=0
Phase 1 — maxProd = 2: Step 1: Fix start index i=0. Single-element subarray [2] product is 2. Initialize maxProd = 2.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: int maxProduct(vector<int>& nums) { int n = nums.size(); int maxProd = nums[0]; for (int i = 0; i < n; ++i) { int prod = 1; for (int j = i; j < n; ++j) { prod *= nums[j]; maxProd = max(maxProd, prod); } } return maxProd; }}; int main() { Solution sol; vector<int> nums = {2, 3, -2, 4}; cout << "Maximum Product Subarray: " << sol.maxProduct(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Two nested loops check all N*(N+1)/2 subarrays in O(N2) time. - Space complexity:
O(1)— Auxiliary space is O(1).
Why Brute Force Doesn't Scale:
At any index i, the best product ending at i only depends on three choices: start fresh with nums[i], extend the previous max product (nums[i] * max_prod), or extend the previous min product (nums[i] * min_prod). By maintaining these two values in scalar registers, we solve the problem in a single pass of N steps.
For N = 20,000: Brute Force takes ~200,000,000 operations (~1s). Dual Kadane takes ~20,000 ops (< 1ms).