Find the Longest Consecutive Run of Ones

Quick Overview

Find the longest contiguous run of ones in a binary array, including boundary runs and all-zero inputs.

Find the Longest Consecutive Run of Ones

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

# Find the Longest Consecutive Run of Ones Given a binary array `nums`, return the length of its longest contiguous run containing only `1` values. A zero breaks a run. ### Interface `class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums); };` ### Example 1 ```text Input: nums = [0,1,1,1,0,1,1,1,1] Output: 4 ``` The two nonempty runs have lengths 3 and 4. The longer run reaches the last array position. ### Example 2 ```text Input: nums = [0,0,0] Output: 0 ``` There is no run containing a 1. ### Constraints - `1 <= nums.length <= 100000`. - Every element is either `0` or `1`. ### What a Strong Answer Covers - Contiguity rather than the total number of ones. - Runs at either boundary, all-one arrays and all-zero arrays. - A correctness argument and time and memory bounds. ```hint A prefix summary What information about a processed prefix lets the next bit extend or end its last run? ```

Overview: Find the longest contiguous run of ones in a binary array, including boundary runs and all-zero inputs.

Google logo
Google
easySoftware EngineerOtherCoding & Algorithms
0
0

Find the Longest Consecutive Run of Ones

Given a binary array nums, return the length of its longest contiguous run containing only 1 values. A zero breaks a run.

Interface

class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums); };

Example 1

Input: nums = [0,1,1,1,0,1,1,1,1]
Output: 4

The two nonempty runs have lengths 3 and 4. The longer run reaches the last array position.

Example 2

Input: nums = [0,0,0]
Output: 0

There is no run containing a 1.

Constraints

  • 1 <= nums.length <= 100000 .
  • Every element is either 0 or 1 .

What a Strong Answer Covers Guidance

  • Contiguity rather than the total number of ones.
  • Runs at either boundary, all-one arrays and all-zero arrays.
  • A correctness argument and time and memory bounds.