Find the Longest Valid Obstacle Course at Each Position

Hard Topics Company Tags

For every index i in obstacles, find the longest non-decreasing subsequence that ends at that index. You may choose any earlier indices, but must preserve their original order and include obstacles[i] as the final value. Adjacent chosen heights may be equal. Return an array containing the length for each index.

Example 1:

Input: obstacles = [4,4,2,5]

Output: [1,2,1,3]

Explanation: The courses ending at successive indices can be [4], [4,4], [2], and [4,4,5]. Their lengths are [1,2,1,3].

Example 2:

Input: obstacles = [7,6,5]

Output: [1,1,1]

Explanation: Every earlier height is larger than the current height, so each valid course consists only of its final obstacle. All lengths are 1.

Example 3:

Input: obstacles = [2,1,2,3]

Output: [1,1,2,3]

Explanation: The longest courses ending at each position can be [2], [1], [2,2], and [2,2,3], with lengths [1,1,2,3].

Constraints:

  • 1 <= obstacles.length <= 100000
  • 1 <= obstacles[i] <= 10000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.