Introduction
Number of LIS is an advanced variation of the Longest Increasing Subsequence problem.
Instead of finding:
Length of LIS we need to find:
How many LIS exist.Example
nums = [1,3,5,4,7] Output:
2 Explanation:
LIS #1
[1,3,5,7]
LIS #2[1,3,4,7]
Total:
2 Key Observation
For every index:
Track:Length and CountTwo DP arrays:
length[i] = Length of LIS ending at i Recurrence
If:
nums[j] < nums[i] and we find a longer sequence:
length[j] + 1 > length[i] Then:
length[i] = length[j] + 1count[i] = count[j]If we find another LIS of same length:
length[j] + 1 == length[i] Then:
count[i] += count[j] Dry Run
Input:
[1,3,5,4,7] Length Array:
[1,2,3,3,4] Count Array:
[1,1,1,1,2] Maximum Length:
4 Answer:
2 Approach : Dynamic Programming
Explanation
For each element:
- Check all previous elements.
- Extend increasing subsequences.
- Update length array.
- Update count array.
- Sum counts having maximum LIS length.