Count Number of Nice Subarrays
Real-world version: Runs With K Odd ReadingsThe statement here is our own: the same inputs, outputs and technique.
A flow meter logs one positive whole number per minute, and the array readings holds the shift in order. A run is any block of consecutive minutes, so it is fixed by the minute it opens on and the minute it closes on, and it always covers at least one minute.
The lab audits a run by counting how many of its readings are odd numbers. A run passes the audit when that count comes to exactly k; a run holding fewer odd readings fails, and so does one holding more.
Tally how many runs of readings pass the audit. Two runs count separately whenever they open or close on different minutes, even if the numbers they hold happen to match.
Examples
Example 1
- Input
- readings = [7, 12, 5, 4, 4, 9], k = 2
- Output
- 5
Odd readings sit at minutes 0, 2 and 5. The runs holding exactly two of them are [7, 12, 5], [7, 12, 5, 4], [7, 12, 5, 4, 4], [12, 5, 4, 4, 9] and [5, 4, 4, 9].
Example 2
- Input
- readings = [4, 8, 12], k = 1
- Output
- 0
Every reading on this shift is even, so no run can reach an odd count of one.
Example 3
- Input
- readings = [3, 5, 7], k = 2
- Output
- 2
All three readings are odd, so a passing run has to cover exactly two neighbouring minutes: [3, 5] or [5, 7].
Constraints
- 1 <= readings.length <= 50000
- 1 <= readings[i] <= 10^5
- 1 <= k <= readings.length
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 runs_with_k_odd_readings(readings: list[int], k: int) -> int:public int runsWithKOddReadings(int[] readings, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 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
- Binary Subarrays With SumReal-world version: Stretches With Exact Press CountMedium
- Minimum Operations to Reduce X to ZeroReal-world version: Loading Crates From Both EndsMedium
- Continuous Subarray SumReal-world version: Billing Window on the Water MeterMedium
- Sorted GCD Pair QueriesReal-world version: Gear Mesh QueriesHard