Typing Class Progress

Mediumdynamic programmingAlso known as Longest Increasing Subsequence

A night-school typing class records each student's speed, in words per minute, at the end of every session. Speeds go up and down: a tired evening, a hard text, a good night's sleep. At the end of term the teacher writes a progress note that quotes some of the sessions, in date order, where each quoted speed is strictly faster than the one quoted before it.

The longer the chain of improving sessions, the more encouraging the note. What is the longest chain she can quote for a student?

Your task

Write longestImprovement(speeds). Return the length of the longest list of sessions you can pick, keeping their original order, where each picked speed is strictly greater than the previous picked speed. The picked sessions do not need to be next to each other.

An empty record gives 0. Equal speeds do not count as an improvement.

longestImprovement(speeds: int[]) → int

Examples

Example 1
Input
speeds = [42, 38, 45, 40, 47, 41, 43, 50]
Output
5
Why

Quote 38, 40, 41, 43, 50. Starting with the first session, 42, gets you at most 42, 45, 47, 50, which is 4. The best chain starts with a dip.

Example 2
Input
speeds = [30, 30, 30]
Output
1
Why

Every session is the same speed. A chain needs each speed to be strictly faster, so the best is one session on its own.

Constraints

  • 0 ≤ speeds.length ≤ 2,500
  • 0 ≤ speeds[i] ≤ 200
Start with brute force

Try every subset of sessions, check whether it is strictly increasing, and keep the longest. With 2,500 sessions there are 2²⁵⁰⁰ subsets. Even 40 sessions means about a trillion.

Two quick shortcuts are wrong. The longest run of consecutive rising sessions misses chains that skip bad days. Greedily taking every session that beats the last one you took fails on [1, 9, 2, 3, 4]: it takes 1, 9 and gets stuck.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code