Polski

Longest increasing subsequence

Pick the longest strictly increasing subsequence from a series of measurements – and return it, not just its length. The classic O(n²) DP, then "patience sorting" with binary search in O(n log n).

hard · typescript · javascript · python · csharp · java · go · 40 XP

An analyst looks at successive performance results of an application (benchmark scores of consecutive builds) and wants to chart the longest story of continuous improvement: pick as many builds as possible (not necessarily adjacent, but in the original order) whose scores strictly increase.

Task

Return one of the longest strictly increasing subsequences of nums – as a list of values in order of appearance. If there are several, any of them is correct (the tests check the length, that it increases, and that it is a subsequence of the input). For an empty array – an empty list.

Signatures: longestIncreasingSubsequence(nums) (JS/TS), longest_increasing_subsequence(nums) (Python), Solution.LongestIncreasingSubsequence (C#, List<int>), Solution.longestIncreasingSubsequence (Java, List<Integer>), LongestIncreasingSubsequence (Go, []int).

Examples

numsSample resultLength
[10, 9, 2, 5, 3, 7, 101, 18][2, 3, 7, 18] (or [2, 5, 7, 101] …)4
[0, 1, 0, 3, 2, 3][0, 1, 2, 3]4
[7, 7, 7, 7][7] – "strictly" rules out equal values1
[][]0

Constraints

  • 0 ≤ n ≤ 100,000, values in the 32-bit int range.

Expected complexity

O(n log n) time, O(n) memory. An O(n²) solution is correct but will not fit in the time limit for 100,000 elements.