Code Logo

Lantern Melody Chain Length

Published at05 Jan 2026
Hard 2 views
Like9

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

Example 1
Input
melodies = [5,4,3]
Output
1
Explanation

Since the numbers keep going down, the best chain is just one number long.

Example 2
Input
melodies = []
Output
0
Explanation

With no melodies, the chain length is zero.

Example 3
Input
melodies = [1,3,2,3,4]
Output
4
Explanation

A strong rising chain here is [1,2,3,4], which has length 4.

Algorithm Flow

Recommendation Algorithm Flow for Lantern Melody Chain Length
Recommendation Algorithm Flow for Lantern Melody Chain Length

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].

dp[i] = 1 + max(dp[j]) for all j < i where melodies[j] < 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

java
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;
    }
}