We have an array that only contains 0's and 1's, and we need to find the longest run of consecutive 1's. It is like counting the longest winning streak in a series of games where 1 means a win and 0 means a loss.
As we scan through the array, we maintain a running count of consecutive 1's. Every time we reach a 0, the streak breaks and the count resets. At each step, we record the largest count seen so far. The difficulty here is not the algorithm but implementing the scan without off-by-one errors.
1 <= nums.length <= 10^5 → With n up to 100,000, we need O(n) or O(n log n). An O(n^2) approach (checking every subarray) would be 10 billion operations, which is too slow.nums[i] is either 0 or 1 → This is a binary array. We don't need to worry about negative numbers, large values, or any other edge cases related to element values. The only two states are "part of a streak" or "streak breaker."For every position in the array, count how long the run of consecutive 1's starting at that position is. The answer is the maximum of those counts across all starting positions. Pick a starting index, count how many 1's follow in a row, record that length, move to the next starting index, and repeat.
maxCount = 0 to track the best streak found.i from 0 to n - 1:nums[i] is 1, start counting consecutive 1's from index i.i, incrementing a counter while elements are 1.maxCount with the streak length if it's larger.maxCount.The brute force recounts the same 1's from every starting position inside a run. A single pass that keeps a running count, growing it on each 1 and resetting it on each 0, avoids that repeated work.
There is no need to restart counting from each position. Walk through the array once, keeping a running counter. On a 1, increment the counter. On a 0, the streak is broken, so reset the counter to 0. After each element, compare the current streak against the longest seen so far.
The counter maintains an invariant: count always holds the length of the run of 1's ending at the current position. On a 1 the run extends by one; on a 0 no run ends here, so the count drops to 0. Every maximal run of 1's ends at some index, and at that index count equals the full run length. Updating maxCount after every element therefore compares against each run's true length, including a run in the middle of the array that a later 0 breaks.
This is a simplified Kadane's algorithm. Kadane's tracks the best subarray sum ending at each position; here we track the longest run of 1's ending at each position. Both maintain a local running value, reset it at the right moment, and keep the global best.
maxCount = 0 and count = 0.nums.1, increment count.0, reset count to 0.maxCount = max(maxCount, count).maxCount.count and maxCount). No extra data structures regardless of input size.