Minimum cost to fill given weight in a bag
Pattern: Subsequences and knapsack
Packets of i + 1 kg cost cost[i] (-1 means not sold), and you may buy any number. best[w] is the cheapest way to make exactly w kg: unbounded knapsack with min.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
cost[i] is the price of a packet of i + 1 kg, or -1 if that size is not sold. Return the least cost to buy exactly
W kg, or -1 if impossible. The catalogue has no practice link for this one.
Think first
- Which earlier problem is this?
- What does -1 mean for a packet?
- What if no combination reaches W?
Hints
Brute force, and why it fails
Try every combination of packets: exponential.
The key insight
Each weight's cheapest cost depends only on lighter weights.
Dry run
cost [20, 10, 4, 50, 100], W = 5.
Step 1 of 2
The plan
best = [0, inf, ...]
for w: for each sold size s: best[w] = min(best[w], best[w - s] + cost)
return -1 if inf
Complexity
- Time
O(W²)- Space
O(W)
Up to W sizes per weight.
Edge cases
- No sizes sold: -1.
- W = 1.
- Only large packets.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minimumCost(int[] cost, int W) { // cost[i]: price of a packet weighing i + 1 kg, -1 if not sold
final int INF = Integer.MAX_VALUE;
int[] best = new int[W + 1]; // best[w]: the cheapest way to make exactly w kg
Arrays.fill(best, INF);
best[0] = 0;
for (int w = 1; w <= W; w++)
for (int i = 0; i < cost.length && i + 1 <= w; i++)
if (cost[i] != -1 && best[w - i - 1] != INF) best[w] = Math.min(best[w], best[w - i - 1] + cost[i]); // unlimited packets
return best[W] == INF ? -1 : best[W];
}
}C++
class Solution {
public:
int minimumCost(vector<int>& cost, int W) { // cost[i]: price of a packet weighing i + 1 kg, -1 if not sold
const int INF = INT_MAX;
vector<int> best(W + 1, INF); // best[w]: the cheapest way to make exactly w kg
best[0] = 0;
for (int w = 1; w <= W; w++)
for (int i = 0; i < static_cast<int>(cost.size()) && i + 1 <= w; i++)
if (cost[i] != -1 && best[w - i - 1] != INF) best[w] = min(best[w], best[w - i - 1] + cost[i]); // unlimited packets
return best[W] == INF ? -1 : best[W];
}
};Python
class Solution:
def minimumCost(self, cost: list[int], W: int) -> int: # cost[i]: price of a packet of i + 1 kg, -1 if not sold
INF = float("inf")
best = [0] + [INF] * W # best[w]: the cheapest way to make exactly w kg
for w in range(1, W + 1):
for i, c in enumerate(cost):
if c != -1 and i + 1 <= w: # unlimited packets
best[w] = min(best[w], best[w - i - 1] + c)
return -1 if best[W] == INF else best[W]Common mistakes
- Using -1 as a price.
- Returning infinity.