Music streaming app~45 min2s · 256 MBtarget O(s x budget x q) time, O(budget x q) spacedp · knapsack
A video player downloads a video in segments, and it can pick a bitrate for each segment: a larger bitrate means a larger download and a better picture. The viewer has a data budget for the whole video, so the sizes of all the chosen segments must add up to at most the budget.
Changing the bitrate between two neighbouring segments is visible as a jump in quality, so the player charges a fixed penalty for every change. It wants the highest total quality, minus the penalties.
Write best_session(sizes, quality, budget, penalty).
s segments, each with the same number q of bitrate options.i, option j has download size sizes[i][j] and quality quality[i][j].budget.penalty for every pair of neighbouring segments whose chosen options differ.-1 when no choice fits the budget. (Every quality is at least 100 and the penalty is at most 100, so a real score is never below 100.)Input: sizes = [[10, 20, 40], [10, 20, 40], [10, 20, 40]], quality = [[100, 250, 300], [100, 250, 300], [100, 250, 300]], budget = 80, penalty = 60
Output: 750Each segment offers three options: size 10 for quality 100, size 20 for 250, size 40 for 300. The budget is 80 and a switch costs 60. These are the best choices of options, writing 1, 2 and 3 for small, medium and large:
| Choice | Total size | Total quality | Switches | Score |
|---|---|---|---|---|
| 2, 2, 2 | 60 | 750 | 0 | 750 |
| 3, 2, 2 | 80 | 800 | 1 | 740 |
| 2, 2, 3 | 80 | 800 | 1 | 740 |
| 2, 3, 2 | 80 | 800 | 2 | 680 |
| 2, 2, 1 | 50 | 600 | 1 | 540 |
The best score is 750: keeping the medium option throughout. The higher quality of 800 is not worth a switch.
Input: sizes = [[10, 20], [10, 20]], quality = [[100, 300], [100, 300]], budget = 15, penalty = 0
Output: -1The cheapest choice uses 20 units, above the budget of 15, so nothing fits.
Input: sizes = [[30, 60]], quality = [[200, 500]], budget = 100, penalty = 40
Output: 500One segment, so no switching: the best option within the budget is the second, with quality 500.
1 ≤ sizes.length ≤ 40 (segments); quality has the same shape, with the same number of options in every row, between 1 and 41 ≤ sizes[i][j] ≤ 100 and 100 ≤ quality[i][j] ≤ 1,0001 ≤ budget ≤ 1,500 (data units), 0 ≤ penalty ≤ 100Trying every choice means 4^40 combinations, about 10^24, so brute force is out. The budget is small, at most 1,500 units, so a table indexed by the amount used is affordable: 40 segments × 1,501 amounts × 4 options is about 240,000 states. The state must also remember the last option, because the penalty depends on whether the next option is the same.