Busking Set List

Mediumdynamic programmingAlso known as 0/1 Knapsack

A street musician has a fixed-length slot at a weekend market. For each song she knows how long it lasts and roughly how much it earns. Crowds dislike repeats, so she plays each song at most once.

She wants to know which songs fit in the slot and earn 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. The best single earner, the 5-minute song worth 10, leaves 2 minutes in which nothing fits, so 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 therefore between 5 and 11, and the answer is 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, which is about a million for 20 songs and an impossible 10³⁰ for 100.

Greedy rules are tempting and wrong. Taking the best earner first picks the 5-minute song in the first example and ends with 10 instead of 13. Taking 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 picks 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