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.
We want the longest subsequence with at most k transitions (places where adjacent elements differ). For this hard version, the constraints are larger, so we need to optimize the DP by compressing the state and using hash maps for only relevant states.
classSolution {
publicintmaximumLength(int[] nums, int k) {
Map<Long, Integer> dp =new HashMap<>();
int ans = 0;
for(int x : nums) {
Map<Long, Integer> ndp =new HashMap<>();
ndp.put(((long)x<<5), 1);
for(var e : dp.entrySet()) {
int v = (int)(e.getKey()>>5), t = (int)(e.getKey()&31);
int nt = t + (v!=x?1:0);
if(nt<=k) {
long nk = ((long)x<<5)|nt;
ndp.put(nk, Math.max(ndp.getOrDefault(nk, 0), e.getValue()+1));
}
}
for(int l : ndp.values()) ans = Math.max(ans, l);
dp = ndp;
}
return ans;
}
}
classSolution {
funmaximumLength(nums: IntArray, k: Int): Int {
var dp = mutableMapOf<Pair<Int,Int>,Int>()
var ans = 0for (x in nums) {
val ndp = mutableMapOf<Pair<Int,Int>,Int>()
ndp[x to 0] = 1for ((key, l) in dp) {
val(v, t) = key
val nt = t + if (v != x) 1else0if (nt <= k) {
val nk = x to nt
ndp[nk] = maxOf(ndp.getOrDefault(nk,0), l+1)
}
}
for (l in ndp.values) ans = maxOf(ans, l)
dp = ndp
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaximumLength(self, nums: list[int], k: int) -> int:
dp = dict() # (val, t) -> max len ans =0for x in nums:
ndp = dict()
ndp[(x, 0)] =1for (v, t), l in dp.items():
nt = t + (v != x)
if nt <= k:
nk = (x, nt)
ndp[nk] = max(ndp.get(nk, 0), l+1)
for l in ndp.values():
ans = max(ans, l)
dp = ndp
return ans
use std::collections::HashMap;
impl Solution {
pubfnmaximum_length(nums: Vec<i32>, k: i32) -> i32 {
letmut dp = HashMap::new(); // (val, t) -> max len
letmut ans =0;
for&x in&nums {
letmut ndp = HashMap::new();
ndp.insert((x, 0), 1);
for (&(v, t), &l) in&dp {
let nt = t +if v != x { 1 } else { 0 };
if nt <= k {
let nk = (x, nt);
ndp.insert(nk, ndp.get(&nk).copied().unwrap_or(0).max(l+1));
}
}
for&l in ndp.values() { ans = ans.max(l); }
dp = ndp;
}
ans
}
}