You are given an integer array nums and a non-negative integer k. A sequence of integers seq is called good if there are at mostk indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1].
Return the maximum possible length of a good subsequence of nums.
Example 1:
1 2 3 4 5 6 7
Input: nums = [1,2,1,1,3], k = 2
Output: 4
Explanation:
The maximum length subsequence is `[1,2,1,1,3]`.
Example 2:
1 2 3 4 5 6 7
Input: nums = [1,2,3,4,5,1], k = 0
Output: 2
Explanation:
The maximum length subsequence is `[1,2,3,4,5,1]`.
classSolution { public: intmaximumLength(vector<int>& nums, int k){ // the definition of dp: // dp[i][j] marks the longest sequence ending with i, with at most k mismatches // state transition: // dp[i][j] can be transitioned with dp[i][j] + 1 // dp[i][j] can be transitioned from mx[i - 1] + 1 map<int, vector<int>> dp; vector<int> mx(k + 1, 0); // the mx, the m1, the m2 for (int num : nums) { if (!dp.contains(num)) { dp[num] = vector<int>(k + 1, 0); } for (int i = k; i >= 0; i--) { dp[num][i]++; if (i) { dp[num][i] = max(dp[num][i], mx[i - 1]+ 1); } if (dp[num][i] > mx[i]) { mx[i] = dp[num][i]; } } } return mx[k]; } };