Problem
You are given 3 positive integers zero
, one
, and limit
.
A binary array arr
is called stable if:
- The number of occurrences of 0 in
arr
is exactlyzero
. - The number of occurrences of 1 in
arr
is exactlyone
. - Each subarray of
arr
with a size greater thanlimit
must contain both 0 and 1.
Return the total number of stable binary arrays.
Since the answer may be very large, return it modulo 10^9 + 7
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= zero, one, limit <= 1000
Solution
Method 1 – Dynamic Programming with Prefix Sums
Intuition
We want to count all binary arrays with exactly zero
0s and one
1s, such that no subarray of length > limit
is all 0s or all 1s. This is a classic DP with prefix sums optimization: for each state, we can place up to min(zero, limit)
0s or up to min(one, limit)
1s in a row, then switch.
Approach
- Let
dp[z][o][last]
be the number of ways to arrangez
zeros ando
ones, ending withlast
(0 or 1). - For each state, try placing
cnt
consecutive 0s (if last is 1) or 1s (if last is 0), forcnt
in 1 tomin(zero, limit)
ormin(one, limit)
. - Use prefix sums to speed up the transitions.
- Initialize base cases: if only zeros or only ones left, only valid if count ≤ limit.
- Sum the ways starting with 0 and with 1.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(zero * one * limit)
, as each state is visited and transitions up to limit. - 🧺 Space complexity:
O(zero * one)
, for the DP table.