LeetCode 2370: Longest Ideal Subsequence
Problem Description
Explanation
To find the length of the longest ideal subsequence, we can use a dynamic programming approach. We can define a 2D array dp
where dp[i][j]
represents the length of the longest ideal subsequence ending at index i
with a difference of j
between the last two characters. We can then iterate over the string s
and update the dp
array based on the current character and the previous characters.
Algorithm:
- Initialize a 2D array
dp
of sizen x 26
wheren
is the length of the strings
and 26 represents the number of lowercase letters. - Initialize all values in
dp
with 0. - Iterate over each character in the string
s
:- For each character
c
at indexi
, consider all possible charactersprev
that can precedec
such that the difference betweenc
andprev
is less than or equal tok
. - Update the
dp[i][c - 'a']
with the maximum value ofdp[prevIndex][prevChar - 'a'] + 1
for all validprev
characters.
- For each character
- Find the maximum value in the last row of
dp
to get the length of the longest ideal subsequence.
Time Complexity:
The time complexity of this algorithm is O(n * k) where n is the length of the string s
.
Space Complexity:
The space complexity of this algorithm is O(n * 26) = O(n) where n is the length of the string s
.
Solutions
Solutions
class Solution {
public int longestIdealSubsequence(String s, int k) {
int n = s.length();
int[][] dp = new int[n][26];
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
for (char prev = 'a'; prev <= 'z'; prev++) {
int prevIndex = i - 1;
while (prevIndex >= 0 && Math.abs(c - prev) <= k) {
dp[i][c - 'a'] = Math.max(dp[i][c - 'a'], dp[prevIndex][prev - 'a'] + 1);
prevIndex--;
}
}
}
int maxLen = 0;
for (int j = 0; j < 26; j++) {
maxLen = Math.max(maxLen, dp[n - 1][j]);
}
return maxLen;
}
}
Loading editor...