Number of Longest Increasing Subsequences
Count how many longest strictly increasing subsequences an array has, by tracking the best length and its number of ways at each position.
Given an integer array nums
Example 1
Output: 2
Explanation: [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2
Output: 5
Explanation: the longest length is 1, and each of the five 2s is one such subsequence.
The Idea
Picture the numbers 1, 3, 5, 4 and 7 as stepping stones across a stream, read from left to right. You cross by stepping on some of them in order, and each stone you step on must be higher than the last one. You may skip stones, but never go back.
The longest crossings in Example 1 step on four stones: 1, 3, 5, 7 and 1, 3, 4, 7. Each crossing is a strictly increasing subsequence, and two of them have the longest length, so the answer is 2. In Example 2 no stone is higher than another, so every crossing is a single stone, and there are five of those.
Five stones are easy to check by hand, but a longer array has far too many crossings to write out. How can we count the longest ones without listing them?
Look at where a crossing ends. Every increasing subsequence that ends at 7 is either 7 alone, or one ending at a smaller number to the left of 7, with 7 added. So for each number it is enough to know two things: the length of the longest increasing subsequence ending there, and how many subsequences of that length end there.
Look at the picture below. The row labelled "longest increasing subsequence ending here" reads 1, 2, 3, 3, 4. The row labelled "how many of that length end here" reads 1, 1, 1, 1, 2.
Follow the arrows into 7. Both 5 and 4 are smaller than 7, and each ends an increasing subsequence of length 3 that is reached in 1 way: 1, 3, 5 and 1, 3, 4. Adding 7 to either gives length 4, so 7 gets length 4, reached in 1 + 1 = 2 ways. No number has a longer length, so the answer is 2.
So the two numbers at 7 come straight from the numbers already worked out for 5 and 4. Filling both rows from left to right, each entry built from entries to its left instead of listing subsequences again, is called dynamic programming.
Solution Approach
Turning that idea into code means comparing it with listing every subsequence, then settling three things: the starting values of the two rows, how a smaller earlier number updates them, and how the answer is added up.
Listing every subsequence
Why not write out every increasing subsequence and count the longest? Each number is either in a subsequence or left out, so five numbers give 25 = 32 choices, and thirty numbers already give over a billion. The two rows need only one look back over the earlier numbers for each number.
Starting values
What does a number have before it looks to its left? On its own, it is an increasing subsequence of length 1, and there is exactly one of it. So both rows start at 1 at every position. In Example 2, no 2 is bigger than an earlier 2, so both rows stay at 1 everywhere.
Extending from a smaller earlier number
What happens when an earlier number is smaller than the current one? Each of its longest subsequences can be extended by the current number, giving a length one more than its own. Compare that length with the best length found so far at the current number:
- Longer: it is the new best length. The count found so far belonged to shorter subsequences, so it is replaced by the earlier number's count.
- Equal: these are more ways to reach the same length, so the earlier number's count is added.
- Shorter: nothing changes, because those subsequences are not the longest ones ending here.
Take the 7 in Example 1. It looks at 1, 3 and 5 in turn, and each one raises its length, ending at 4 with the count 1 copied from 5. Then 4 also gives length 4, an equal length, so its count of 1 is added and 7 ends with 2.
Adding up the answer
Where do the longest subsequences end? Not always at one number. In Example 2 every 2 ends a longest subsequence of length 1, so the answer adds the counts at all five positions. So keep the longest length seen so far, and a running total of the counts at positions that reach it. A longer length restarts the total, and an equal one adds to it.
Java Solution
The method findNumberOfLIS
- First, create two arrays as long as
:nums , wherelength is the length of the longest increasing subsequence ending atlength[i] , andnums[i] , wherecount is how many subsequences of that length end there. Two variables start at 0:count[i] , the longest length seen so far, andlongest , the running total of counts at that length.total - An outer loop moves
over the array. It setsi andlength[i] to 1, forcount[i] on its own.nums[i] - Inside it, a second loop moves
over the positions beforej . Wheni , the extension has lengthnums[j] < nums[i] . If that beatslength[j] + 1 , it becomeslength[i] andlength[i] becomescount[i] . If it equalscount[j] ,length[i] is added tocount[j] .count[i] - After the inner loop, compare
withlength[i] . A bigger length becomeslongest andlongest restarts attotal . An equal length addscount[i] tocount[i] .total - When the outer loop ends, the method prints both arrays, so the output shows the two rows, and returns
.total
The main
import java.util.Arrays;
public class NumberOfLongestIncreasingSubsequences {
public static int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[] length = new int[n]; // longest increasing subsequence ending at i
int[] count = new int[n]; // how many of that length end at i
int longest = 0;
int total = 0;
for (int i = 0; i < n; i++) {
length[i] = 1; // nums[i] on its own
count[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (length[j] + 1 > length[i]) { // a longer way: take j's count
length[i] = length[j] + 1;
count[i] = count[j];
} else if (length[j] + 1 == length[i]) { // another way to the same length
count[i] += count[j];
}
}
}
if (length[i] > longest) { // a new longest length
longest = length[i];
total = count[i];
} else if (length[i] == longest) { // more of the longest length
total += count[i];
}
}
System.out.println(" length = " + Arrays.toString(length)); // the two tables
System.out.println(" count = " + Arrays.toString(count));
return total;
}
public static void main(String[] args) {
int[][] tests = {
{1, 3, 5, 4, 7},
{2, 2, 2, 2, 2},
{1, 2, 4, 3, 5, 4, 7, 2},
{1, 1, 2, 2},
{5, 4, 3, 2, 1},
{}
};
for (int[] nums : tests) {
System.out.println(Arrays.toString(nums));
System.out.println(" answer = " + findNumberOfLIS(nums));
}
}
}
Running it prints:
[1, 3, 5, 4, 7]
length = [1, 2, 3, 3, 4]
count = [1, 1, 1, 1, 2]
answer = 2
[2, 2, 2, 2, 2]
length = [1, 1, 1, 1, 1]
count = [1, 1, 1, 1, 1]
answer = 5
[1, 2, 4, 3, 5, 4, 7, 2]
length = [1, 2, 3, 3, 4, 4, 5, 2]
count = [1, 1, 1, 1, 2, 1, 3, 1]
answer = 3
[1, 1, 2, 2]
length = [1, 1, 2, 2]
count = [1, 1, 2, 2]
answer = 4
[5, 4, 3, 2, 1]
length = [1, 1, 1, 1, 1]
count = [1, 1, 1, 1, 1]
answer = 5
[]
length = []
count = []
answer = 0
For [1, 3, 5, 4, 7]lengthcount
The array [1, 2, 4, 3, 5, 4, 7, 2]count[i]count[j]
For [1, 1, 2, 2]total[5, 4, 3, 2, 1]
Complexity
The work is the two loops: each number looks back once at every number before it.
- Time: O(n²), because each of the n numbers checks all the numbers to its left, about n²/2 comparisons in all, each followed by at most one update.
- Space: O(n), because the
andlength arrays hold one entry for each number incount .nums
Finding only the longest length, without counting the subsequences, is covered in