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
import java.util.*;
class Solution {
public int calculate_chain_length(int[] notes) {
if (notes.length == 0) return 0;
int[] tails = new int[notes.length];
int len = 0;
for (int x : notes) {
int i = 0, j = len;
while (i != j) {
int m = (i + j) / 2;
if (tails[m] < x) i = m + 1;
else j = m;
}
tails[i] = x;
if (i == len) len++;
}
return len;
}
}Related Dynamic Programming Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
