[LeetCode] Number of Stable Subsequences

3686. Number of Stable Subsequences

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 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int countStableSubsequences(vector<int>& nums) {
long long dp[2][3] {{0,0,0},{0,0,0}};
long long mod = 1e9 + 7;
for(auto& n : nums) {
int p = n & 1;
dp[p][2] = (dp[p][2] + dp[p][1]) % mod;
dp[p][1] = (dp[p][1] + dp[!p][1] + dp[!p][2] + 1) % mod;
}
return (dp[0][1] + dp[0][2] + dp[1][1] + dp[1][2]) % mod;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/09/19/PS/LeetCode/number-of-stable-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.