
Sponsored
Sponsored
Solve with full IDE support and test cases
Use these hints if you're stuck. Try solving on your own first.
Let <code>dp[x][y][z = 0/1]</code> be the number of stable arrays with exactly <code>x</code> zeros, <code>y</code> ones, and the last element is <code>z</code>. (0 or 1). <code>dp[x][y][0] + dp[x][y][1]</code> is the answer for given <code>(x, y)</code>.
If we have already placed <code>x</code> 1 and <code>y</code> 0, if we place a group of <code>k</code> 0, the number of ways is <code>dp[x-k][y][1]</code>. We can place a group with size <code>i</code>, where <code>i</code> varies from 1 to <code>min(limit, zero - x)</code>. Similarly, we can solve by placing a group of ones.
Speed up the calculation using prefix arrays to store the sum of <code>dp</code> states.