1. Brute Force (Nested Loop with Zero Counter)
Intuition
Try every possible starting index i. Expand rightwards with index j. Count how many zeros appear. If zeros <= k, record length j - i + 1. Update max length.
Algorithm
- Step 1: Initialize
maxLen = 0. - Step 2: For each i from 0 to n - 1:
- - Initialize
zeros = 0. - - For each j from i to n - 1:
- - If
nums[j] == 0,zeros++. - - If
zeros > k, break. - -
maxLen = max(maxLen, j - i + 1). - Step 3: Return
maxLen.
Brute Force (Nested Loop with Zero Counter) 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=1.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: int longestOnes(std::vector<int>& nums, int k) { int n = nums.size(); int maxLen = 0; for (int i = 0; i < n; i++) { int zeros = 0; for (int j = i; j < n; j++) { if (nums[j] == 0) zeros++; if (zeros > k) break; maxLen = std::max(maxLen, j - i + 1); } } return maxLen; }}; int main() { Solution sol; std::vector<int> nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}; std::cout << "Max 1s: " << sol.longestOnes(nums, 2) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Nested Loop with Zero Counter). - Space complexity:
O(1)— Space complexity for Brute Force (Nested Loop with Zero Counter).
Why Brute Force Doesn't Scale:
For N = 100,000, N2 = 1010 operations (over 10 seconds). The two-pointer sliding window guarantees linear time O(N), processing 100,000 elements in < 5 milliseconds.
With N = 100,000: Brute force takes ~10 billion operations; Sliding window completes in ~200,000 operations (~50,000x faster).