Number of Stable Subsequences Problem
Description
LeetCode Problem 3686.
You are given an integer array nums.
A subsequence is stable if it does not contain three consecutive elements with the same parity when the subsequence is read in order (i.e., consecutive inside the subsequence).
Return the number of stable subsequences.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,3,5]
Output: 6
Explanation:
- Stable subsequences are [1], [3], [5], [1, 3], [1, 5], and [3, 5].
- Subsequence [1, 3, 5] is not stable because it contains three consecutive odd numbers. Thus, the answer is 6.
Example 2:
Input: nums = [2,3,4,2]
Output: 14
Explanation:
- The only subsequence that is not stable is [2, 4, 2], which contains three consecutive even numbers.
- All other subsequences are stable. Thus, the answer is 14.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Dynamic Programming on the Last Run
Only the end of a subsequence matters: its last parity and whether its last two numbers have the same parity (a run of one or two equal parities). Keep four counts f[p][r] of stable subsequences ending with parity p and a run of r (1 or 2), modulo 10^9 + 7.
For a new number with parity p, the old subsequences stay as they are (we skip the number), and we add the subsequences that take it:
- run of one: the number alone, or appended to any subsequence ending with the other parity, which is
1 + f[1-p][1] + f[1-p][2]; - run of two: appended to a subsequence of parity
pwith run one, which isf[p][1].
A subsequence that ends with a run of two cannot be extended by the same parity, so no longer runs are created. The answer is the sum of the four counts.
Complexity: O(n) time and O(1) extra space.
class Solution:
def countStableSubsequences(self, nums: List[int]) -> int:
mod = 10**9 + 7
# f[p][r]: stable subsequences ending with parity p and a run of r (1 or 2) equal parities
f = [[0, 0], [0, 0]]
for x in nums:
p = x % 2
ends_other = f[1 - p][0] + f[1 - p][1]
new_run1 = (f[p][0] + 1 + ends_other) % mod
new_run2 = (f[p][1] + f[p][0]) % mod
f[p][0], f[p][1] = new_run1, new_run2
return (f[0][0] + f[0][1] + f[1][0] + f[1][1]) % mod