726. Bottomless Backpack
A hiker may pack as many copies of each kind of snack as desired, since every kind is sold in unlimited supply. Kind i weighs weights[i] and brings values[i] units of energy. The backpack carries at most capacity in total weight.
Return the largest total energy that can be carried. The pack does not have to be filled completely, a kind may be taken any number of times (including zero), and if nothing fits, the answer is 0. You can assume the answer fits in a 32-bit signed integer.
Aim for time O(n * capacity) and space O(capacity).
Example 1
- Input:
- weights = [7,4,9], values = [15,8,19], capacity = 22
- Output:
- 46
- Explanation:
Two copies of the weight-9 kind and one weight-4 kind weigh exactly 22 and give 19 + 19 + 8 = 46 energy, which no other mix beats.
Example 2
- Input:
- weights = [6,10], values = [7,12], capacity = 5
- Output:
- 0
- Explanation:
Neither kind fits into a capacity of 5, so nothing can be carried.
Constraints
1 ≤ weights.length = values.length ≤ 100
1 ≤ weights[i] ≤ 100
0 ≤ values[i] ≤ 1000
0 ≤ capacity ≤ 10000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n * capacity)
- Space
- O(capacity)