1493. Fewest Rising Chains

Medium3.5 points estimatedBinary SearchGreedyArray

A hiking club records the altitude of each checkpoint in the order they were visited, in the array nums. The club wants to describe the trip as several separate "climbing logs". In one climbing log the checkpoints, read in visiting order, must go strictly upward, and the checkpoints of a log need not be adjacent in the original order.

Every checkpoint must be placed in exactly one log. Return the smallest number of logs that is enough to hold all checkpoints. Only the count is returned, so there is nothing to tie-break. Equal altitudes can never share a log, because the climb must be strict. Aim for O(n log n) time and O(n) extra space; a quadratic scan will be too slow for the largest inputs.

Example 1

Input:
nums = [4,2,5,1,3]
Output:
3
Explanation:

The longest run that never rises is 4,2,1 (length 3), so three logs are needed, e.g. [4,5], [2,3], [1].

Example 2

Input:
nums = [7,7,7]
Output:
3
Explanation:

Equal values cannot share a log, so each of the three needs its own.

Example 3

Input:
nums = [1,2,3,4]
Output:
1
Explanation:

The whole sequence already climbs strictly, so one log suffices.

Constraints

1 ≤ n ≤ 105

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…