1. Nested Loops All Pairs
Intuition
Check every possible pair of lines (i, j) and compute the trapped area min(height[i], height[j]) * (j - i).
Algorithm
- 1. Initialize maxArea = 0.
- 2. For i from 0 to n-1: - For j from i+1 to n-1: - currentArea = min(height[i], height[j]) * (j - i) - maxArea = max(maxArea, currentArea).
- 3. Return maxArea.
Brute Force All Pairs Area Comparison
2 of 2 questions left todayPair (0, 1): First pair evaluation
Pair (0, 1): First pair evaluation. Area is 2. Increment j.
#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 maxArea(vector<int>& height) { int n = height.size(); int maxWater = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int h = min(height[i], height[j]); int w = j - i; maxWater = max(maxWater, h * w); } } return maxWater; }}; int main() { Solution sol; vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7}; cout << "Max Water Area: " << sol.maxArea(height) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Evaluates all N*(N-1)/2 pairs in nested loops, resulting in O(N2) runtime. - Space complexity:
O(1)— Only uses a single integer variable for tracking maximum area. Auxiliary space is O(1).
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.