Music streaming app~25 min2s · 256 MBtarget O(n + R) time, O(R) spaceclassic twin: lc-740dp
A music streaming app runs a weekly game on a queue of tracks. Each track has a rating from 1 to 10,000.
A move picks one rating. Every track with that rating leaves the queue, and each earns as many points as its rating. The tracks rated one higher and one lower also leave, and earn nothing.
Your team lead asks: "What is the most points a player can earn before the queue is empty?"
Write most_points(ratings).
ratings lists the rating of every track in the queue, in any order.r that is still in the queue. Every track rated r leaves and earns r points. Every track rated r - 1 or r + 1 leaves and earns nothing.Input: ratings = [3, 4, 2, 2, 3, 5, 3]
Output: 14Only the count of each rating matters. Choosing rating v takes all its tracks for v * count[v] points, and rules out ratings v - 1 and v + 1. So the ratings are a line, and no two neighbouring ratings are both chosen.
Let best[v] be the most points using ratings up to v. Skip v and keep best[v - 1], or choose it and add its points to best[v - 2].
| v | Tracks | Points | Skip: best[v - 1] | Take: best[v - 2] + points | best[v] |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | ||
| 1 | 0 | 0 | 0 | 0 + 0 = 0 | 0 |
| 2 | 2 | 4 | 0 | 0 + 4 = 4 | 4 |
| 3 | 3 | 9 | 4 | 0 + 9 = 9 | 9 |
| 4 | 1 | 4 | 9 | 4 + 4 = 8 | 9 |
| 5 | 1 | 5 | 9 | 9 + 5 = 14 | 14 |
The answer is best[5] = 14: choose rating 3 for 9 points and rating 5 for 5 points, then rating 2 is gone with 3.
Input: ratings = [4, 4, 4]
Output: 12One rating only. Choosing it takes all three tracks, for 12 points.
Input: ratings = [1, 3, 5]
Output: 9The ratings 1, 3 and 5 are not neighbours in value, so every move is free: 9 points.
1 ≤ len(ratings) ≤ 100,0001 ≤ ratings[i] ≤ 10,000There can be 100,000 tracks, but only 10,000 different ratings. Playing the game in every order never finishes. Counting the tracks of each rating and walking over the ratings costs about 110,000 steps.