#673

Number of Longest Increasing Subsequence

Medium
ArrayDynamic ProgrammingBinary Indexed TreeSegment TreeDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n * n)
O(n²)
Space
O(n)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses dynamic programming to keep track of the lengths of the longest increasing subsequences ending at each index, along with their counts. This significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two arrays, 'lengths' to store the length of the longest increasing subsequence ending at each index, and 'counts' to store the number of such subsequences.
  2. 2Step 2: Iterate through the array, updating 'lengths' and 'counts' based on previous elements.
  3. 3Step 3: Find the maximum length from the 'lengths' array and sum the counts of subsequences that have this maximum length.
solution.py18 lines
1# Full working Python code
2
3def findNumberOfLIS(nums):
4    if not nums:
5        return 0
6    n = len(nums)
7    lengths = [1] * n
8    counts = [1] * n
9    for i in range(n):
10        for j in range(i):
11            if nums[i] > nums[j]:
12                if lengths[j] + 1 > lengths[i]:
13                    lengths[i] = lengths[j] + 1
14                    counts[i] = counts[j]
15                elif lengths[j] + 1 == lengths[i]:
16                    counts[i] += counts[j]
17    max_length = max(lengths)
18    return sum(counts[i] for i in range(n) if lengths[i] == max_length)

Complexity note: The time complexity is O(n²) due to the nested loops iterating through the array, while the space complexity is O(n) for the two arrays used to store lengths and counts.

  • 1Understanding how to track multiple attributes (length and count) is crucial in dynamic programming.
  • 2Recognizing patterns in subsequences can help simplify the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.