Max Consecutive Ones

EasyArrays & Hashinglinear scan

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a binary array nums (every element is either 0 or 1), return the length of the longest contiguous run of 1s in the array. A "run" is a maximal stretch of consecutive positions that all hold the value 1. Your job is to find the single longest such stretch and report how many 1s it contains. If the array contains no 1s at all, the answer is 0.

Examples

Input: nums = [1, 1, 0, 1, 1, 1]
Output: 3
The runs of 1s have lengths 2 and 3. The longest is the trailing run of three 1s.
Input: nums = [1, 0, 1, 1, 0, 1]
Output: 2
The runs of 1s have lengths 1, 2, and 1. The longest is 2.
Input: nums = [0, 0, 0]
Output: 0
There are no 1s in the array, so the longest run has length 0.

Constraints

  • 1 <= nums.length <= 100000
  • Each `nums[i]` is either `0` or `1`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.