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
arris exactlyzero. - The number of occurrences of 1 in
arris exactlyone. - Each subarray of
arrwith a size greater thanlimitmust 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 <= 200
Solution
Method 1 – Dynamic Programming (DP with Last Placed Value)
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 means we cannot have more than limit consecutive 0s or 1s. We can use DP to count the number of ways to build such arrays, keeping track of the last value placed and how many consecutive times it has been placed.
Approach
- Define
dp(z, o, last, cnt)as the number of ways to arrangezzeros andoones, where the last placed value islast(0 or 1), and it has been placedcnttimes consecutively. - Base case: if
z == 0ando == 0, return 1. - If last placed is 0 and
z > 0andcnt < limit, we can place another 0. - If last placed is 1 and
o > 0andcnt < limit, we can place another 1. - We can always switch to the other value if available, resetting the count to 1.
- Use memoization to avoid recomputation.
- Try both starting with 0 and starting with 1, sum the results.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(zero * one * limit * 2), as each state is visited once. - 🧺 Space complexity:
O(zero * one * limit * 2), for memoization.