#3130
Find All Possible Stable Binary Arrays II
HardDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(zero + one)) | O(zero * one * limit) |
| Space | O(1) | O(zero * one) |
💡
Intuition
Time O(zero * one * limit)Space O(zero * one)
We can use dynamic programming to efficiently count the valid stable arrays by breaking the problem into smaller subproblems. This avoids the need to generate all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Define a DP table dp[x][y][z] where x is the number of zeros, y is the number of ones, and z indicates the last element (0 or 1).
- 2Step 2: Initialize base cases for dp where only one '1' is present.
- 3Step 3: Fill the DP table by considering adding groups of zeros or ones, ensuring they do not violate the limit condition.
solution.py12 lines
1def countStableArrays(zero, one, limit):
2 MOD = 10**9 + 7
3 dp = [[[0, 0] for _ in range(one + 1)] for _ in range(zero + 1)]
4 dp[0][1][1] = 1 # Base case: one '1'
5 for x in range(zero + 1):
6 for y in range(1, one + 1):
7 for k in range(1, limit + 1):
8 if x >= k:
9 dp[x][y][1] = (dp[x][y][1] + dp[x - k][y][0]) % MOD
10 if y > 1:
11 dp[x][y][0] = (dp[x][y][0] + dp[x][y - 1][1]) % MOD
12 return (dp[zero][one][0] + dp[zero][one][1]) % MODℹ
Complexity note: This complexity arises from filling a 3D DP table based on the number of zeros, ones, and the limit, leading to a polynomial time complexity.
- 1Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.
- 2Understanding the constraints helps in designing the DP state transitions effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.