Coding problem
Pack the most value within a weight limit
The task
A courier van can carry a limited weight, and each parcel on offer pays a different fee. The dispatcher wants the set of parcels that pays the most without going over the limit.
Complete KnapsackMaxValue(int[] weights, int[] values, int capacity). Item i weighs weights[i] (1 or more) and is worth values[i] (0 or more); the two arrays have the same length. Each item can be packed at most once. Return the largest total value whose total weight is at most capacity (0 or more), as a long.
Signature
public static long KnapsackMaxValue(int[] weights, int[] values, int capacity)
Examples
[2, 5, 3, 4], [6, 11, 7, 9], 8→18. The items of weight 5 and 3 are worth 11 + 7.[1], [7], 3→7. The one item can be packed only once.
Limits: Up to 100 items and a capacity of up to 10,000.
The tests check: no items, an item too heavy, an exact fit, equal items, an item packed once, no capacity, values beyond int, a mix that fills the capacity, and 100 items in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// The largest total value of items, each packed at most once, whose total weight is at most capacity.
public static long KnapsackMaxValue(int[] weights, int[] values, int capacity)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.