Number of Longest Increasing Subsequence
Problem Statement:β
Given an integer arrayΒ nums, returnΒ the number of longest increasing subsequences.
NoticeΒ that the sequence has to beΒ strictlyΒ increasing.
-
Example:
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
β Solution: Tabulation + Count Trackingβ
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, 1); // dp[i] = length of LIS ending at i
vector<int> cnt(n, 1); // cnt[i] = number of LIS ending at i
int maxi = 1; // Length of longest increasing subsequence
for(int i = 0; i < n; i++){
for(int prev = 0; prev < i; prev++){
if(nums[prev] < nums[i]){
if(dp[prev] + 1 > dp[i]){
dp[i] = dp[prev] + 1;
cnt[i] = cnt[prev]; // Reset count from prev
}
else if(dp[prev] + 1 == dp[i]){
cnt[i] += cnt[prev]; // Add more ways to reach same LIS length
}
}
}
maxi = max(maxi, dp[i]);
}
// Count all sequences of maximum length
int ans = 0;
for(int i = 0; i < n; i++){
if(dp[i] == maxi){
ans += cnt[i];
}
}
return ans;
}
};
π How It Worksβ
- You must find how many longest increasing subsequences (LIS) exist in the array.
- Use:
dp[i]: length of LIS ending at indexicnt[i]: number of such LIS of that length ending ati
- For every pair
(prev, i):- If
nums[prev] < nums[i], check:- New longer LIS β update
dp[i]and resetcnt[i] = cnt[prev] - Same length LIS β accumulate
cnt[i] += cnt[prev]
- New longer LIS β update
- If
- Finally, sum all
cnt[i]wheredp[i] == maxLIS.
π§© Key Transitionsβ
if(nums[prev] < nums[i]){
if(dp[prev] + 1 > dp[i]){
dp[i] = dp[prev] + 1;
cnt[i] = cnt[prev];
}
else if(dp[prev] + 1 == dp[i]){
cnt[i] += cnt[prev];
}
}
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(NΒ²) β |
| Space | O(N) β |
β οΈ Edge Casesβ
- All elements equal β every single element is an LIS of length 1
- Strictly increasing β only 1 LIS of length N
- Duplicates with same LIS length β handled via
cnt[i]
π‘ Other Approachesβ
| Method | Notes |
|---|---|
| DFS + Memo | β Too slow (exponential) |
| Segment Tree | β Overkill, hard to maintain count |
| DP + Count β | Most optimal for counting LIS |
π Related Problemsβ
- Longest Increasing Subsequence
- Number of Longest Increasing Subsequence
- Russian Doll Envelopes
- Longest Bitonic Subsequence (GFG)
π Level Up Your Engineering Mindset
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Official Hub
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.