Parcel budget: Boss receipt
Stuck or curious how this works? Visualize 0/1 Knapsack ↗
Inputs
drawers is a list of parcels. Each row is [weight, value].
Your tasks
- Create a list
bestValues. Each row ofdrawersis a parcel: [weight, value]. The weight is positive, and the value is 0 or more. A bag can hold a total weight up to its capacity. For every capacity from 0 throughk, find the largest total value you can pack. You may use each parcel at most once. You may leave parcels out. Put one answer per capacity inbestValues, including capacity 0. - Multiply each number in
bestValuesby its position, counting from 1: the first number by 1, the second by 2, and so on. - Add those products. Store the sum in
weightedTotal. - Complete
parcelBudgetBossReceiptso it returnsweightedTotal. Return it, do not print it.
Example
If drawers is [[8, 7], [5, 5], [7, 8], [8, 10], [5, 8]] and k is 3, then bestValues is [0, 0, 0, 0] and parcelBudgetBossReceipt returns 0.
Rules
k(a whole number from 1 to 8) is the largest bag capacity to check in task 1.
Test data
TEST DATA 1: drawers is [[2, 1], [1, 1], [2, 19], [8, 18], [8, 19]] and k is 3.
TEST DATA 2: drawers is [[1, 8], [8, 8], [1, 10], [1, 11]] and k is 8.
Examples
Input: drawers = [[2,1],[1,1],[2,19],[8,18],[8,19]] k = 3 Output: 139
bestValues is [0, 1, 19, 20]. Multiply by positions that start at 1: 1 * (0) + 2 * (1) + 3 * (19) + 4 * (20) = 139. Return 139.
Input: drawers = [[1,8],[8,8],[1,10],[1,11]] k = 8 Output: 1216
bestValues is [0, 11, 21, 29, 29, 29, 29, 29, 29]. Multiply by positions that start at 1: 1 * (0) + 2 * (11) + 3 * (21) + 4 * (29) + 5 * (29) + 6 * (29) + 7 * (29) + 8 * (29) + 9 * (29) = 1216. Return 1216.
Input: drawers = [] k = 5 Output: 0
bestValues is [0, 0, 0, 0, 0, 0]. Multiply by positions that start at 1: 1 * (0) + 2 * (0) + 3 * (0) + 4 * (0) + 5 * (0) + 6 * (0) = 0. Return 0.
Input limits
- 0 <= input size <= 64.
- k is a whole number from 1 to 8. Answers fit in a signed 32-bit integer: -2,147,483,648 through 2,147,483,647.
- Input numbers have no decimal part. They range from -1,000,000 to 1,000,000. Follow any extra input rules in task 1.
Efficiency goal
Big-O describes how the work or memory needed grows as the input gets larger.
Efficiency goal: time O(n*k); extra memory, including the helper list, O(k). n is the input length. These labels describe how work and memory grow with the input.
Practice focus
Build bestValues first, then return exactly what the tasks ask for. Follow the order, keep repeated values when the rule says so, and check the empty case.