← DiffPush

Count Number of Nice Subarrays

Standard Bar Sliding Window · Medium Problems O(n) · O(1)

The Freight Yard Odd-Cargo Counter

A freight yard tracks wagons, flagging each as carrying odd-classified cargo (1) or not (0 in the parity log). A route segment is 'eventful' when exactly k wagons in it carry odd-classified cargo. The yard clerk needs the number of eventful segments — even-length gaps of even cargo are allowed to pad either side, so segments are counted by position, not by shape.

Input: An integer array nums and an integer k.

Output: Return the number of contiguous subarrays containing exactly k odd numbers.

Constraints

Examples

Example 1

Input: {"nums":[1,1,2,1,1],"k":3}
Output: 2
Only [1,1,2,1] and [1,2,1,1] hold exactly three odd wagons.

Example 2

Input: {"nums":[2,4,6],"k":1}
Output: 0
No wagon carries odd cargo, so no segment can be eventful.

Solve this in your browser →

Also on LeetCode ↗