Suppose we want to build a valid subsequence where the value (A[i] + A[i+1]) % k remains constant for all consecutive elements. For each possible modulo value, we can keep track of the longest subsequence ending with a specific number and having that modulo.
Let DP[currNum][mod] represent the maximum length of a valid subsequence ending with currNum and having the required modulo mod for all consecutive pairs. For each number in the array, we try to extend all possible subsequences for every modulo value from 0 to k-1.
To include currNum in a subsequence with modulo mod, the previous number in the subsequence must satisfy (currNum + prevNum) % k = mod, which rearranges to prevNum = (mod - currNum + k) % k (ensuring non-negative results). Thus, for each mod, we look up the best subsequence ending with prevNum and update DP[currNum][mod] as max(DP[currNum][mod], 1 + DP[prevNum][mod]). We also consider starting a new subsequence with just currNum.
Finally, the answer is the largest value among all DP[num][mod] for all numbers and modulos.
classSolution {
publicintmaximumLength(int[] nums, int k) {
int[][] dp =newint[k][k];
int maxLen = 1;
for (int num : nums) {
int currRem = num % k;
for (int mod = 0; mod < k; ++mod) {
int prevRem = (mod - currRem + k) % k;
dp[currRem][mod]= Math.max(dp[currRem][mod], 1 + dp[prevRem][mod]);
maxLen = Math.max(maxLen, dp[currRem][mod]);
}
}
return maxLen;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmaximumLength(nums: IntArray, k: Int): Int {
val dp = Array(k) { IntArray(k) }
var maxLen = 1for (num in nums) {
val currRem = num % k
for (mod in0 until k) {
val prevRem = (mod - currRem + k) % k
dp[currRem][mod] = maxOf(dp[currRem][mod], 1 + dp[prevRem][mod])
maxLen = maxOf(maxLen, dp[currRem][mod])
}
}
return maxLen
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
from typing import List
classSolution:
defmaximumLength(self, nums: List[int], k: int) -> int:
dp = [[0] * k for _ in range(k)]
max_len =1for num in nums:
curr_rem = num % k
for mod in range(k):
prev_rem = (mod - curr_rem + k) % k
dp[curr_rem][mod] = max(dp[curr_rem][mod], 1+ dp[prev_rem][mod])
max_len = max(max_len, dp[curr_rem][mod])
return max_len
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmaximum_length(nums: Vec<i32>, k: i32) -> i32 {
let k = k asusize;
letmut dp =vec![vec![0; k]; k];
letmut max_len =1;
for&num in&nums {
let curr_rem = (num % k asi32) asusize;
for mod_ in0..k {
let prev_rem = (mod_ asi32- curr_rem asi32+ k asi32) % k asi32;
let prev_rem = prev_rem asusize;
dp[curr_rem][mod_] = dp[curr_rem][mod_].max(1+ dp[prev_rem][mod_]);
max_len = max_len.max(dp[curr_rem][mod_]);
}
}
max_len
}
}