☰ All problems

56. Longest Increasing Subsequence

Given an integer array nums, return the length of its longest strictly increasing subsequence.

A subsequence keeps the original order of the elements but may skip any of them. For example, [1,6,8] is a subsequence of [4,1,6,2,8], while [6,1] is not.

Example 1
Input: nums = [4,1,6,2,7,3,8]
Output: 4

Explanation: Both [4,6,7,8] and [1,2,3,8] have length 4, and nothing longer exists.

Example 2
Input: nums = [0,8,4,12,2,10,6,14,1,9]
Output: 4
Example 3
Input: nums = [5,5,5]
Output: 1

Explanation: Equal values do not count as increasing.

Constraints

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

Follow-up: Can you also reconstruct one longest subsequence, not just its length?

💡 Hint 1

An O(n²) DP works: len[i] = 1 + the largest len[j] with j < i and nums[j] < nums[i].

💡 Hint 2

For O(n log n), keep tails[k] = the smallest possible last value of an increasing subsequence of length k + 1. This array is always sorted.

💡 Hint 3

For each number, binary-search the first tail that is >= it and overwrite it (or append if none). The final length of tails is the answer.

/**
 * @param {number[]} nums
 * @return {number}
 */
function lengthOfLIS(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc