Ctrl K

Lamp Trade in a Window

Hard
A row of street lamps runs along an alley; their state is the string lamps: '1' means the lamp is on, '0' means it is off. The caretaker may make **at most one trade** inside a chosen stretch of the alley: 1. switch off a whole contiguous block of lit lamps that has an unlit lamp on both sides; 2. then switch on a whole contiguous block of unlit lamps that has a lit lamp on both sides. A stretch is a pair [l, r]: lamps l through r inclusive. Inside a stretch the caretaker sees only its own lamps and imagines one extra lit lamp just beyond each end (these imaginary lamps are not counted). The trade only changes lamps inside the stretch. For each stretch in windows, find the largest possible number of lit lamps **in the whole row** after the best trade (or no trade). Stretches are independent: each one starts from the original string. Return the answers as a list in the same order.
Example 1
lamps="0110100", windows=[[0, 6], [3, 6], [1, 2]] → [6, 6, 3]

Three lamps are lit in total. Window [0, 6]: switch off the lit block at position 4, so the dark stretches of length 1 and 2 merge, then switch on all 4 lamps: 3 − 1 + 4 = 6. Window [3, 6] = "0100" allows the same trade, also 6. Window [1, 2] = "11" has no dark stretch, so no trade is possible and the count stays 3.

Example 2
lamps="1010", windows=[[0, 3], [0, 2]] → [4, 2]

In window [0, 3] the stretch is "1010": switch off lamp 2 (it sits between dark lamps 1 and 3) and switch on lamps 1–3, giving 4. In window [0, 2] = "101" lamp 2 is at the window edge; beyond the edge everything counts as lit, so it is not enclosed by dark lamps and the answer is 2.

Constraints
  • 1 ≤ len(lamps) ≤ 10⁵, lamps consists of '0' and '1'
  • 1 ≤ len(windows) ≤ 10⁵
  • windows[i] = [l, r], 0 ≤ l ≤ r < len(lamps)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
loading Python…
Input
lamps="0110100", windows=[[0, 6], [3, 6], [1, 2]]
Expected
[6, 6, 3]

Run checks the first 3 tests in your browser. Submit checks all 45 tests on the server, hidden ones included.