Contiguous Array
Real-world version: Balanced Shift StretchThe statement here is our own: the same inputs, outputs and technique.
A press logs one entry per hour for a whole run: states[i] is 1 when the press was cutting during hour i and 0 when it sat idle.
Maintenance wants the longest block of consecutive hours in which the press spent exactly as many hours cutting as it spent idle. Return the number of hours in that block.
Return 0 when no such block exists. The log can hold up to 10^5 hours, so checking every block separately is too slow.
Examples
Example 1
- Input
- states = [1, 1, 0, 1, 0]
- Output
- 4
Hours 1 through 4 hold two cutting hours and two idle hours. Adding hour 0 would tip the count to three cutting hours, so 4 is the longest.
Example 2
- Input
- states = [1, 1, 1, 1]
- Output
- 0
The press never idled, so no block can be balanced and the answer is the sentinel 0.
Example 3
- Input
- states = [0, 1, 0, 0, 1, 1]
- Output
- 6
Across the whole log there are three idle hours and three cutting hours, so the entire run is balanced.
Constraints
- 1 <= states.length <= 10^5
- states[i] is either 0 or 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def longest_balanced_stretch(states: list[int]) -> int:public int longestBalancedStretch(int[] states)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Check if All the Integers in a Range Are CoveredReal-world version: Patrol Coverage AuditEasy
- Subarray Sum Equals KReal-world version: Trail Elevation StretchesMedium
- Count Number of Nice SubarraysReal-world version: Runs With K Odd ReadingsMedium
- Count Subarrays With Majority Element IReal-world version: Stretches Carried by One CandidateMedium