Lantern Melody Chain Length
You are given a list of melody values, and the goal is to find the length of the longest increasing subsequence.
A subsequence does not need to use neighboring elements, but it must keep the original left-to-right order. That means you may skip values, but you are not allowed to rearrange them.
For example, if melodies = [5,4,3], the answer is 1 because nothing rises, so the best subsequence is just one value. If melodies = [1,3,2,3,4], the answer is 4 because one valid increasing subsequence is [1,2,3,4].
So the task is to look through the sequence and keep the longest chain that stays strictly increasing while preserving the original order.
Example Input & Output
Since the numbers keep going down, the best chain is just one number long.
With no melodies, the chain length is zero.
A strong rising chain here is [1,2,3,4], which has length 4.
Algorithm Flow
Solution Approach
The most direct dynamic programming idea is to let dp[i] mean the length of the longest increasing subsequence that ends exactly at index i.
Then for each position i, we look at all earlier positions j. If melodies[j] < melodies[i], then the subsequence ending at j can be extended by melodies[i].
If no earlier value is smaller, then dp[i] = 1 because the subsequence can start at i.
After filling the DP array, the answer is the largest value in dp. This runs in O(n^2) time and is easy to explain. There is also a faster O(n log n) approach, but the DP version is usually the clearest starting point.
Best Answers
class Solution {
public int calculate_chain_length(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m+1][n+1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = s.charAt(i-1)==t.charAt(j-1) ? dp[i-1][j-1]+1 : Math.max(dp[i-1][j], dp[i][j-1]);
return dp[m][n];
}
}Related Dynamic Programming Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
