PROBLEM LINK:
Author: Konstantin Sokol
Tester: Tasnim Imran Sunny
Editorialist: Praveen Dhinwa
DIFFICULTY:
EASY-MEDIUM
PREREQUISITES:
greedy, sorting
PROBLEM:
You are given N items, each item has two parameters: the weight and the cost. Let’s denote M as the sum of the weights of all the items.
Your task is to determine the most expensive cost of the knapsack, for every capacity 1, 2, …, M.
The capacity C of a knapsack means that the sum of weights of the chosen items can’t exceed C.
QUICK EXPLANATION
-
We can greedily start picking the most costliest items with weight <= 2, which can be taken in the knapsack.
EXPLANATION
For a weight W, can you find the most expensive cost of the knapsack ?
Assume that W is even, we can first select the most expensive items with sum of weights <= 2.
We can do his in following ways.
-
Take the most expensive item of weight 2.
-
Or take the at most two most expensive item of weight 1.
Note that after picking most expensive items with sum of weights <= 2, we will remove the items taken and will recursively
select the items to fill the knapsack with most expensive elements.
Note that if W is odd, then we can simply select the most expensive knapsack of weight 1. Now we won’t consider this item again.
Now we have to select at most W - 1 most expensive weights from the remaining items. Note that W - 1 is even, we can solve this problem
similar to previous problem.
Note that during finding the most expensive cost for the knapsack of weight W, we also find the answer for W - 2. So we can
find answer for all the even W’s in single iteration. We will use another iteration to find answer for odd weights. Please
view the pseudo code to understand more about it.
Pseudo code
// Let "one" denote the array with items with weight 1 sorted in increasing order of cost.
// Let "two" denote the array with items with weight 2 sorted in increasing order of cost.
// First we will construct answer for weights being even.
long long cur = 0;
// iterate over even weights.
// let ans[w] be the answer for the weight w.
for (int w = 2; w <= W; w += 2) {
// pick the most expensive atmost 2 elements and take those items into knapsack.
// let their sum of their costs be cost.
cur += cost;
ans[w] = cur;
}
// Now we will construct answer for weights being odd.
long long cur = 0;
// iterate over odd weights.
// let ans[w] be the answer for the weight w.
if (one.size() >= 1) {
// pick the highest weighed item with weight = 1.
cur = one[one.size() - 1];
one.remove(one.size() - 1);
ans[1] = cur;
}
for (int w = 3; w <= W; w += 2) {
// pick the most expensive atmost 2 elements and take those items into knapsack.
// let their sum of their costs be cost.
cur += cost;
ans[w] = cur;
}
Complexity
N log N, as we are only doing sorting of two arrays of size at most N.
For a reference implementation, please refer to editorialist’s solution.