Longest Run of Consecutive Ones

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given a binary array nums containing only 0s and 1s, return the length of the longest run of consecutive 1s in the array. Checking every starting index and walking forward works, but it re-derives information a single pass already has: whether the current streak is still alive. The sliding windowSliding WindowMaintaining a running result over a contiguous range that grows or shrinks one element at a time, instead of recomputing the result for every range from scratch. idea shows up here in its simplest form — a streak counter that grows by one on every 1 and collapses to 0 on every 0, with the best value seen along the way kept as the answer.

Test Case 1:

Input:nums = [1, 1, 0, 1, 1, 1]
Output:3
Explanation:The run [1, 1, 1] at the end (indices 3-5) is the longest streak of 1s.

Test Case 2:

Input:nums = [1, 0, 1, 1, 0, 1]
Output:2
Explanation:The run [1, 1] (indices 2-3) is the longest streak.

Test Case 3:

Input:nums = [0, 0, 0]
Output:0
Explanation:There isn't a single 1 in the array, so the longest run has length 0.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is either 0 or 1
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int longestRunOfOnes(int[] nums) {
3 int maxLen = 0, count = 0;
4 for (int i = 0; i < nums.length; i++) {
5 if (nums[i] == 1) {
6 count++;
7 maxLen = Math.max(maxLen, count);
8 } else {
9 count = 0;
10 }
11 }
12 return maxLen;
13 }
14}
15
1
1
0
1
1
1
0
1
2
3
4
5
Variables
maxLen0
count0
INITIALIZE

Start maxLen and count both at 0. Scan the array once, left to right.

Step 1 / 19

Approach & Solutions

Brute Force

Brute

For every starting index, walk forward counting how many 1s appear in a row before hitting a 0 or the end of the array, and track the longest run seen. Correct, but for an array of all 1s every starting index re-walks almost the entire rest of the array.

TimeO(n²)
SpaceO(1)
1class Solution { 2 public int longestRunOfOnes(int[] nums) { 3 int maxLen = 0; 4 for (int i = 0; i < nums.length; i++) { 5 int len = 0; 6 for (int j = i; j < nums.length && nums[j] == 1; j++) { 7 len++; 8 } 9 maxLen = Math.max(maxLen, len); 10 } 11 return maxLen; 12 } 13}

Optimal — Single Pass

Optimal

Scan the array once, keeping a running streak counter. Every time you see a 1, extend the streak and compare it against the best seen so far. Every time you see a 0, the streak breaks — reset the counter to 0 and keep going. No backtracking, no re-walking.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int longestRunOfOnes(int[] nums) { 3 int maxLen = 0, count = 0; 4 for (int i = 0; i < nums.length; i++) { 5 if (nums[i] == 1) { 6 count++; 7 maxLen = Math.max(maxLen, count); 8 } else { 9 count = 0; 10 } 11 } 12 return maxLen; 13 } 14}

Related Problems