1. Brute Force (Nested Loop Subarray Max)
Intuition
Fix start index i. Expand rightwards with index j, keeping a running maximum maxVal = max(maxVal, nums[j]). If maxVal > right, break (any larger subarray starting at i is also invalid). If left <= maxVal <= right, increment answer.
Algorithm
- Step 1: Initialize
ans = 0. - Step 2: For each i from 0 to n - 1:
- - Initialize
maxVal = 0. - - For each j from i to n - 1:
- -
maxVal = max(maxVal, nums[j]). - - If
maxVal > right, break. - - If
maxVal >= left,ans++. - Step 3: Return
ans.
Brute Force (Nested Loop Subarray Max) Trace
2 of 2 questions left todayPhase 1 — Window Initialization: Both left and right pointers anchor at index 0
Phase 1 — Window Initialization: Both left and right pointers anchor at index 0. Initial window length is 1 with sum/metric=2.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: int numSubarrayBoundedMax(std::vector<int>& nums, int left, int right) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; i++) { int maxVal = 0; for (int j = i; j < n; j++) { maxVal = std::max(maxVal, nums[j]); if (maxVal > right) break; if (maxVal >= left) ans++; } } return ans; }}; int main() { Solution sol; std::vector<int> nums = {2, 1, 4, 3}; std::cout << "Subarrays: " << sol.numSubarrayBoundedMax(nums, 2, 3) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Nested Loop Subarray Max). - Space complexity:
O(1)— Space complexity for Brute Force (Nested Loop Subarray Max).
Why Brute Force Doesn't Scale:
For N = 100,000, N2 = 1010 operations, causing TLE. The single-pass 3-state tracking counts valid starting points in O(1) per element, completing in ~100,000 operations (< 3 ms).
For N = 100,000: Brute force takes ~10 billion operations; Single-pass tracking takes ~100,000 operations (~100,000x speedup).