Dynamic programming · Medium
A shipping planner chooses a subset of indivisible packages. Each has a weight and a benefit value; the vehicle has a fixed capacity. Package identities are their input positions, so two equal packages are still separate choices.
Return the maximum benefit achievable without exceeding capacity or selecting any package more than once.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "weights": number[], "values": number[], "capacity": number }.
Fields
- weights and values are equal-length arrays. weights[i] and values[i] describe one package.
- capacity is an integer weight limit.
Output
Return value
- Return a numeric maximum benefit. Choosing no packages is allowed and gives 0.
- Total weight may equal capacity. Do not split or reuse a package.
- Return only the value, not selected indexes.
Constraints
- 0 <= weights.length = values.length <= 1000; 1 <= weights[i] <= 10000.
- 0 <= values[i] <= 1000000 and 0 <= capacity <= 10000.
- The maximum total value is 1000000000 and fits exactly in Number.
Examples
Example 1
{
"capacity": 5,
"values": [
4,
5,
7
],
"weights": [
2,
3,
4
]
}Returns
9Choose the first two packages.
Example 2
{
"capacity": 4,
"values": [
7
],
"weights": [
2
]
}Returns
7One package cannot be selected twice.
Required complexity
O(n * (capacity + 1)) time and O(capacity + 1) extra space