Busking Set List

Mediumdynamic programmingAlso known as 0/1 Knapsack

A street musician has a slot at a weekend market, and the slot is a fixed number of minutes. From past weekends she knows, for each song she can play, how long it lasts and roughly how much money it brings in. Crowds get bored of repeats, so she plays each song at most once.

Which songs should she pick so the set fits in the slot and earns the most?

Your task

Write maxTips(lengths, tips, limit). Song i lasts lengths[i] minutes and earns tips[i]. Choose any set of songs, each used at most once, with total length at most limit, and return the largest possible total of tips.

The order of songs does not matter, and she may leave time unused. With no songs, or if nothing fits, return 0.

maxTips(lengths: int[], tips: int[], limit: int) → int

Examples

Example 1
Input
lengths = [5, 4, 3]
tips = [10, 7, 6]
limit = 7
Output
13
Why

The 4-minute and 3-minute songs fit exactly and earn 7 + 6 = 13. Starting with the best earner, the 5-minute song for 10, leaves 2 minutes, where nothing fits. The best single song is not part of the best set.

Example 2
Input
lengths = [2, 6]
tips = [5, 11]
limit = 6
Output
11
Why

Playing the 2-minute song three times would earn 15, but each song can be played only once. The choice is 5 or 11, so 11.

Constraints

  • 0 ≤ lengths.length = tips.length ≤ 100
  • 1 ≤ lengths[i] ≤ 1,000
  • 0 ≤ tips[i] ≤ 10,000
  • 0 ≤ limit ≤ 1,000
Start with brute force

Try every subset of songs, keep those that fit, and take the best total. That is 2ⁿ subsets: about a million for 20 songs, and an impossible 10³⁰ for 100.

Greedy rules are tempting and wrong. Picking the best earner first takes the 5-minute song in the first example and ends with 10 instead of 13. Picking the best money per minute first also fails: with songs of 1, 5 and 5 minutes earning 3, 10 and 10 and a 10-minute slot, it grabs the 1-minute song first and ends with 13 instead of 20.

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