1. Nested Loops All Subarrays
Intuition
Check every starting position i and extend subarray while elements are 1, tracking max length.
Algorithm
- 1. Initialize maxLen = 0.
- 2. For i from 0 to n-1: - If nums[i] == 1, iterate j from i to n-1 while nums[j] == 1. - maxLen = max(maxLen, j - i).
- 3. Return maxLen.
Nested Loops All Subarrays
2 of 2 questions left todayPhase 1 — Start from Index 0: Check subarray starting at index 0
Phase 1 — Start from Index 0: Check subarray starting at index 0. nums[0]=1, nums[1]=1, nums[2]=0 (streak broken). Length = 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 findMaxConsecutiveOnes(vector<int>& nums) { int n = nums.size(); int maxLen = 0; for (int i = 0; i < n; ++i) { if (nums[i] == 1) { int count = 0; for (int j = i; j < n && nums[j] == 1; ++j) { count++; } maxLen = max(maxLen, count); } } return maxLen; }}; int main() { Solution sol; vector<int> nums = {1, 1, 0, 1, 1, 1}; int ans = sol.findMaxConsecutiveOnes(nums); cout << "Max Consecutive Ones: " << ans << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— In the worst case (all 1s), the nested loop checks O(N2) elements. - Space complexity:
O(1)— 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.