Number of Longest Increasing Subsequence

Count distinct longest increasing subsequences — DP carrying (length, count) per index.

Medium
Time O(n^2) Space O(n)
LeetCode
4 min read
dp

Problem#

Count distinct longest increasing subsequences in nums.

Examples#

  • [1,3,5,4,7]2
  • [2,2,2,2]5

Constraints#

  • 1 <= n <= 2000.

Approach#

Two arrays: len[i] = LIS length ending at i; cnt[i] = count of such LISes. For each pair j < i with nums[j] < nums[i]: if len[j] + 1 > len[i], take over (len[i] = len[j] + 1; cnt[i] = cnt[j]); else if equal, add (cnt[i] += cnt[j]). Sum cnt[i] over all i with max len[i].

Solution#

Number of Longest Increasing Subsequence
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> len(n, 1), cnt(n, 1);
int maxLen = 1;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (len[j] + 1 > len[i]) { len[i] = len[j] + 1; cnt[i] = cnt[j]; }
else if (len[j] + 1 == len[i]) cnt[i] += cnt[j];
}
}
maxLen = max(maxLen, len[i]);
}
int total = 0;
for (int i = 0; i < n; ++i) if (len[i] == maxLen) total += cnt[i];
return total;
}
};

Editorial#

Two parallel DPs — length and count — let us track “how many ways” alongside “how long”. The take-over vs add condition is the canonical “new max” vs “tie” branch.

Complexity#

  • Time: O(n²).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.