Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-763greedy
A radio app cuts a long playlist into consecutive blocks for its listeners. Each track belongs to an artist, and all the tracks of one artist must stay in the same block.
A block also needs at least min_size tracks, or it feels too short on the air. The team wants as many blocks as possible. They can always merge a short block into a neighbour, but cannot split an artist.
Write most_segments(tracks, min_size).
tracks[i] is the artist of track i.min_size tracks.0 when no cutting works, which happens when the whole playlist has fewer than min_size tracks.Input: tracks = [7, 7, 2, 5, 2, 9, 9, 4], min_size = 3
Output: 2The solution scans the playlist and finds the points where a cut is allowed. A cut is allowed where everything before shares no artist with everything after. It cuts at the earliest allowed point at which the block has enough tracks.
| Block ends at index | Tracks in the block so far | Cut? |
|---|---|---|
| 1 (artist 7 is done) | 2 | no, 2 is less than 3 |
| 4 (artist 2 is done) | 5 | yes: block 1 is indexes 0 to 4 |
| 6 (artist 9 is done) | 2 | no, 2 is less than 3 |
| 7 (artist 4 is done) | 3 | yes: block 2 is indexes 5 to 7 |
The answer is 2. Cutting after index 1 would leave a block of 2 tracks, which is too short.
Input: tracks = [1, 2], min_size = 3
Output: 0The whole playlist has 2 tracks, which is fewer than 3, so no block of 3 tracks can be made.
Input: tracks = [1, 2, 1, 3], min_size = 1
Output: 2Artist 1 spans the first three tracks, so they must share a block. The track by artist 3 is a block of one.
1 ≤ len(tracks) ≤ 100,000, and 1 ≤ tracks[i] ≤ 1,000,0001 ≤ min_size ≤ 100,000Trying every pair of cut points takes about 5,000,000,000 pairs, and each needs a check that no artist is split. A single left-to-right scan with a note of each artist's last track finds every allowed cut in one pass, about 100,000 steps.