← Questions

Longest ON run with k range flips

0
AmazonCodingLast asked Apr 2026

A data center rack holds n servers in a row. Their states are given as a binary string server_states, where '1' means the server is ON and '0' means it is OFF.

An operator may run a range flip at most k times. A range flip picks any contiguous block of servers [i, j] and toggles every server in it: ON becomes OFF and OFF becomes ON. Flips may overlap.

Return the length of the longest contiguous run of ON servers that can exist after at most k range flips.

def max_consecutive_on(server_states: str, k: int) -> int: ...

Constraints

  • 0 <= n <= 2 * 10^5
  • 0 <= k <= n
  • server_states contains only '0' and '1'

Example 1

server_states = "0110100", k = 1
output: 4

Flip [3, 3] to get 0111100. That gives a run of 4 (indices 1–4). Flipping [0, 0] instead gives 1110100, a run of only 3.

Example 2

server_states = "1001011", k = 2
output: 7

Flip [1, 2] and [4, 4], and every server is ON.

Note: a flip that covers an ON server turns it OFF, so a flip is not the same as setting a range to ON.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding