Typing Class Progress

Mediumdynamic programmingAlso known as Longest Increasing Subsequence

A night-school typing class records each student's speed, in words per minute, after every session. Speeds go up and down. At the end of term the teacher's progress note quotes some sessions, in date order, each strictly faster than the one quoted before it.

She wants the longest such chain for each student.

Your task

Write longestImprovement(speeds). Return the length of the longest list of sessions you can pick, in their original order, where each picked speed is strictly greater than the previous one. Picked sessions need not 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

The best chain is 38, 40, 41, 43, 50, which has length 5. Starting with the first session, 42, gives at most 42, 45, 47, 50, which has length 4, so 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 and keep the longest strictly increasing one. With 2,500 sessions there are 2²⁵⁰⁰ subsets; even 40 sessions gives about a trillion.

Two 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 taken 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