#2407
Longest Increasing Subsequence II
HardArrayDivide and ConquerDynamic ProgrammingBinary Indexed TreeSegment TreeQueueMonotonic QueueDynamic ProgrammingBinary SearchSegment Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses dynamic programming combined with a data structure (like a Segment Tree or Binary Indexed Tree) to efficiently track the longest increasing subsequence that satisfies the conditions. This approach reduces the time complexity significantly by avoiding the need to check all subsequences.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array to store the maximum length of subsequences ending with each value.
- 2Step 2: Iterate through the nums array, and for each element, check previous elements to see if they can form a valid subsequence with the current element.
- 3Step 3: Use a data structure to efficiently query and update the maximum lengths for valid subsequences.
solution.py13 lines
1def longestIncreasingSubsequence(nums, k):
2 from sortedcontainers import SortedList
3 dp = SortedList()
4 for num in nums:
5 idx = dp.bisect_right(num)
6 if idx > 0:
7 max_length = dp[idx - 1] + 1
8 else:
9 max_length = 1
10 dp.add(num)
11 if idx < len(dp):
12 dp[idx] = max(max_length, dp[idx])
13 return len(dp)ℹ
Complexity note: The time complexity is O(n log n) due to the use of a sorted data structure for efficient querying and updating of the maximum lengths. The space complexity is O(n) because we store the lengths of subsequences in a map or similar structure.
- 1The problem combines the concepts of subsequences and constraints on differences, making it a unique challenge.
- 2Dynamic programming can significantly reduce the complexity of problems involving subsequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.