Find the Longest Binary Window Requiring at Most K Zero Flips

Quick Overview

Find the Longest Binary Window Requiring at Most K Zero Flips. You may change at most k zero entries of binary nums to1.

Find the Longest Binary Window Requiring at Most K Zero Flips

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem You may change at most k zero entries of binary `nums` to1. Return the greatest length of a consecutive run of ones achievable after those changes. ```cpp class Solution { public: int longestOnes(vector<int>& nums, int k); }; ``` ### Examples **Example 1:** ```text Input: nums = [1,0,1,1,0,1], k = 1 Output: 4 Explanation: The first four positions can become all ones with one flip; every length-five window has two zeros. ``` **Example 2:** ```text Input: nums = [0,0,1], k = 0 Output: 1 Explanation: No flips are available, so only the final one forms a nonempty run. ``` ### Constraints - `1 <= nums.length <= 10^5`. - Each value is0 or1. - `0 <= k <= nums.length`. ### Contract considerations Only zeros need changing, and the selected positions need not be adjacent; the resulting run itself must be contiguous. ```hint Read the boundary condition Count zeros in a candidate run rather than simulating choices of individual flips. ``` ### Boundary reminders Only zeros need changing, and the selected positions need not be adjacent; the resulting run itself must be contiguous.

Overview: Find the Longest Binary Window Requiring at Most K Zero Flips. You may change at most k zero entries of binary nums to1.

Amazon logo
Amazon
Aug 30, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

You may change at most k zero entries of binary nums to1. Return the greatest length of a consecutive run of ones achievable after those changes.

class Solution {
public:
    int longestOnes(vector<int>& nums, int k);
};

Examples

Example 1:

Input: nums = [1,0,1,1,0,1], k = 1
Output: 4
Explanation: The first four positions can become all ones with one flip; every length-five window has two zeros.

Example 2:

Input: nums = [0,0,1], k = 0
Output: 1
Explanation: No flips are available, so only the final one forms a nonempty run.

Constraints

  • 1 <= nums.length <= 10^5 .
  • Each value is0 or1.
  • 0 <= k <= nums.length .

Contract considerations

Only zeros need changing, and the selected positions need not be adjacent; the resulting run itself must be contiguous.

Boundary reminders

Only zeros need changing, and the selected positions need not be adjacent; the resulting run itself must be contiguous.