Dynamic programming · Hard
A mobile reader chooses indivisible content packages for offline storage. The UI must show the actual selected packages, not just their total value. Equal-value plans should use less storage and remain deterministic.
Return the best package selection, minimizing used capacity on value ties and choosing the lexicographically smallest index list on remaining ties.
Input
Call
- Implement solve({capacity, packages}); return the chosen plan.
Packages
- capacity is the available storage in abstract whole units, not bytes.
- packages[i].size consumes storage; packages[i].value is its non-negative usefulness.
- The package identity is its index. Identical-looking packages are distinct items.
Output
Plan
- Return {value, used, indices}; used cannot exceed capacity.
- First maximize summed value; among those plans minimize summed size.
- Among remaining plans choose the lexicographically smallest ascending index array.
- For an empty selection return {value: 0, used: 0, indices: []}. Never select an index twice.
Constraints
- 0 <= capacity <= 10000; 0 <= packages.length <= 500.
- 1 <= size <= 10000; 0 <= value <= 1000000. Totals fit signed 32-bit integers.
Examples
Example 1
{
"capacity": 5,
"packages": [
{
"size": 2,
"value": 4
},
{
"size": 3,
"value": 5
},
{
"size": 5,
"value": 8
}
]
}Returns
{
"value": 9,
"used": 5,
"indices": [
0,
1
]
}Example 2
{
"capacity": 4,
"packages": [
{
"size": 4,
"value": 5
},
{
"size": 2,
"value": 5
}
]
}Returns
{
"value": 5,
"used": 2,
"indices": [
1
]
}Required complexity
O(packages × capacity) time and O(packages × capacity) space