Challenge: Pack the Bag
Completed
A hiker's bag holds at most W kg. Each item has a weight and a value and can be packed once or not at all. Print the biggest total value that fits.
Input
Line 1: n W (W ≤ 104). Then n lines weight value.
Output
The best total value.
Example
Input
4 8 1 15 3 50 4 60 5 90
Output
140
Editor
Java
Hints
dp[i][w] = best value with the first i items and capacity w.
Leave item i: dp[i-1][w]. Take it (if it fits): val + dp[i-1][w - weight].
Solution explanation
The table has (n + 1) × (W + 1) cells, each filled in O(1): O(n·W).
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), W = sc.nextInt();
int[] wt = new int[n], val = new int[n];
for (int i = 0; i < n; i++) {
wt[i] = sc.nextInt();
val[i] = sc.nextInt();
}
long[][] dp = new long[n + 1][W + 1];
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
dp[i][w] = dp[i - 1][w];
if (wt[i - 1] <= w) dp[i][w] = Math.max(dp[i][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]);
}
}
System.out.println(dp[n][W]);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module