Music streaming app~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-300binary-search · dp
A music app records how many times a song was played on each day. A label wants to describe the song's growth. Pick some days, in order, so that each picked day has a strictly higher play count than the one before.
The picked days do not need to be next to each other. How many days can you pick at most?
Write longest_rising(plays).
plays[i] is the number of plays on day i.i1 < i2 < ... < ik so that plays[i1] < plays[i2] < ... < plays[ik]. Equal counts do not rise.k, which is 0 when there are no days.Input: plays = [3, 1, 4, 1, 5, 9, 2, 6]
Output: 4Keep a list tails. The entry tails[i] is the smallest last play count of any rising sequence of length i + 1 found so far. For each day, a binary search finds the first tail that is not below the day's count, and the day replaces it, or is added to the end.
| Day's plays | Search finds | tails after the day |
|---|---|---|
| 3 | position 0 (empty list, so add) | [3] |
| 1 | position 0, replace 3 | [1] |
| 4 | position 1 (past the end, add) | [1, 4] |
| 1 | position 0, replace 1 with 1 | [1, 4] |
| 5 | position 2 (add) | [1, 4, 5] |
| 9 | position 3 (add) | [1, 4, 5, 9] |
| 2 | position 1, replace 4 | [1, 2, 5, 9] |
| 6 | position 3, replace 9 | [1, 2, 5, 6] |
The list has 4 entries, so the answer is 4. One rising sequence of length 4 is 3, 4, 5, 9.
Input: plays = []
Output: 0With no days, nothing can be picked.
Input: plays = [5, 5, 5, 5]
Output: 1Equal counts do not rise, so only one day can be picked.
0 ≤ plays.length ≤ 100,0000 ≤ plays[i] ≤ 1,000,000 (plays of one song on day i)Checking, for every day, the best sequence that ends there against every earlier day costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. You need about n log n, which is 1.7 million steps. That points to a binary search inside one pass over the days.