DevPath

← All problems

Longest Increasing Subsequence

Medium dynamic-programming · binary-search

Description

Return the length of the longest strictly increasing subsequence.

Constraints

1 <= n <= 100000

Examples

Input: nums = [10,9,2,5,3,7,101,18]

Output: 4

2,3,7,101

Hints (1)
  • Keep the smallest possible tail for each subsequence length.

Solutions

Patience sorting with binary search. · Time O(n log n) · Space O(n)

func lengthOfLIS(nums []int) int {
    tails := []int{}
    for _, n := range nums {
        lo, hi := 0, len(tails)
        for lo < hi {
            mid := (lo + hi) / 2
            if tails[mid] < n {
                lo = mid + 1
            } else {
                hi = mid
            }
        }
        if lo == len(tails) {
            tails = append(tails, n)
        } else {
            tails[lo] = n
        }
    }
    return len(tails)
}

Create a free account to submit solutions, track progress and save problems.

Create account