LeetCode 2370: Longest Ideal Subsequence Solution
Master LeetCode problem 2370 (Longest Ideal Subsequence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2370. Longest Ideal Subsequence
Problem Explanation
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
dpof sizen x 26wherenis the length of the stringsand 26 represents the number of lowercase letters. - Initialize all values in
dpwith 0. - Iterate over each character in the string
s:- For each character
cat indexi, consider all possible charactersprevthat can precedecsuch that the difference betweencandprevis less than or equal tok. - Update the
dp[i][c - 'a']with the maximum value ofdp[prevIndex][prevChar - 'a'] + 1for all validprevcharacters.
- For each character
- Find the maximum value in the last row of
dpto 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
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2370 (Longest Ideal Subsequence)?
This page provides optimized solutions for LeetCode problem 2370 (Longest Ideal Subsequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2370 (Longest Ideal Subsequence)?
The time complexity for LeetCode 2370 (Longest Ideal Subsequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2370 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2370 in Java, C++, or Python.