Algorithm Day88 - Longest Increasing Subsequence
š§© Problem Description
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
š¬ Examples
Example 1
1 | Input: nums = [10,9,2,5,3,7,101,18] |
Example 2
1 | Input: nums = [0,1,0,3,2,3] |
Example 3
1 | Input: nums = [7,7,7,7,7,7,7] |
š” Approaches
1) Dynamic Programming (O(n²))
Let dp[i] be the length of the longest increasing subsequence ending at index i.
Transition: for each j < i, if nums[j] < nums[i] then dp[i] = max(dp[i], dp[j] + 1).
Answer is max(dp[i]) over all i.
2) Patience Sorting / Greedy + Binary Search (O(n log n))
Maintain an array tails[len] where tails[k] is the smallest possible tail value of an increasing subsequence with length k+1.
For each number x in nums, binary search the first index in tails with value ā„ x and replace it with x. If x is greater than all tails, append it. The length of tails is the LIS length.
This method gives O(n log n) time and O(n) space and is the recommended optimal solution for large inputs.
š¢ Java Code ā DP (O(n²))
1 | class Solution { |
š¢ Java Code ā Patience Sorting (O(n log n))
1 | import java.util.*; |
Note: Collections.binarySearch returns -(insertionPoint) - 1 when the key is not found; the code above converts it into the insertion point.
ā± Complexity Analysis
- DP: Time O(n²), Space O(n).
- Patience Sorting: Time O(n log n), Space O(n).
āļø Summary
- Use DP for clarity or small
n. - For large inputs, use the O(n log n) approach with
tails+ binary search (often called patience sorting). - The
tailsarray stores the smallest possible tail for an increasing subsequence of each length; its size equals the LIS length.