Lv.3dpknapsack
0/1 Knapsack
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Item i has weight weights[i] and value values[i]. Each item is either taken whole or not at all. Return the maximum total
value whose total weight is at most capacity.
Examples
| weights | values | capacity | result |
|---|---|---|---|
[6, 4, 3, 5] | [13, 8, 6, 12] | 7 | 14 |
[10] | [5] | 9 | 0 |
[1, 2, 3] | [10, 15, 40] | 6 | 65 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(weights: int[], values: int[], capacity: int) → long
Constraints
- ,
weights[i],values[i],capacity - The answer can exceed 32 bits.
Expected complexity
- Time
- O(N * W)
- Space
- O(W)
Examples
| weights | values | capacity | Expected |
|---|---|---|---|
[6,4,3,5] | [13,8,6,12] | 7 | 14 |
[10] | [5] | 9 | 0 |
[1,2,3] | [10,15,40] | 6 | 65 |
Hint
Hint
best[w] = max(best[w], best[w - wt] + val) for each item, iterating w downward so an item is used at most once; 64-bit
values. Trying all subsets exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 8 | verdict only |
| performance | 60 | 4 | verdict only |