PROBLEM LINK:
Author: arnie8991
Editorialist: arnie8991
DIFFICULTY:
MEDIUM
PREREQUISITES:
0-1 Knapsack
EXPLANATION:
This problem is just a slight modification of the classic 0-1 Knapsack problem that can be easily solved by using dynamic programming. We only need to take care of the poisoned apples which we can either remove from the list or assign a high cost and low nutritional value.
SOLUTIONS:
[details="Setter’s Solution]
// 1. remove poisoned apples
// 2. We can assign a very high cost and a very low nutrition to the poisoned apples
import java.util.*;
class Main{
public static int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[][] = new int[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = Math.max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
public static void main(String args[]){
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int b = sc.nextInt();
int m = sc.nextInt();
int cost_arr[] = new int[n];
int nutrition_arr[] = new int[n];
int poi_arr[] = new int[b];
for(int i = 0;i<n;++i){ cost_arr[i] = sc.nextInt(); }
for(int i = 0;i<n;++i){ nutrition_arr[i] = sc.nextInt(); }
for(int i = 0;i<b;++i){ poi_arr[i] = sc.nextInt(); }
for(int i: poi_arr){
cost_arr[i] = 9999999;
nutrition_arr[i] = -9999999;
}
int result = knapSack(m, cost_arr, nutrition_arr, n);
System.out.println(result);
}
}
// Time complexity : O(NW)
// Space Complexity: O(NW)
[details=“Tester’s Solution”]