Coding problem · Easy · Basics
Longest Run of Ones
Easy Algorithms & data structures
nums contains only 0s and 1s. Return the length of the longest run of consecutive 1s.
Example 1
Input: nums = [1,1,0,1,1,1] Output: 3
Example 2
Input: nums = [0,0] Output: 0
Hints
Hint 1
Count the current run; reset it to 0 when you see a 0.
Hint 2
Track the best run seen so far.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
One pass with two counters: current grows on 1 and resets on 0, best keeps the maximum.
Reference solution
function maxConsecutiveOnes(nums) {
let best = 0, current = 0;
for (const n of nums) {
current = n === 1 ? current + 1 : 0;
best = Math.max(best, current);
}
return best;
}
function maxConsecutiveOnes(nums: number[]): number {
let best = 0, current = 0;
for (const n of nums) {
current = n === 1 ? current + 1 : 0;
best = Math.max(best, current);
}
return best;
}
def max_consecutive_ones(nums: list[int]) -> int:
best = current = 0
for n in nums:
current = current + 1 if n == 1 else 0
best = max(best, current)
return best
<?php
function maxConsecutiveOnes(array $nums): int
{
$best = $current = 0;
foreach ($nums as $n) {
$current = $n === 1 ? $current + 1 : 0;
$best = max($best, $current);
}
return $best;
}
class Solution {
public int maxConsecutiveOnes(int[] nums) {
int best = 0, current = 0;
for (int n : nums) {
current = n == 1 ? current + 1 : 0;
best = Math.max(best, current);
}
return best;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy