Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Experiment 7

Student Name: Nitish Agarwal UID: 20BCS9392


Branch: CSE Section/Group: 20BCS-MM-804/A
Semester: 5th Date of Performance: 10/11/2022
Subject Name: DAA Lab Subject Code: 20CSP-312

1. Aim/Overview of the practical: Understand the implementation of 0-1 Knapsack using Dynamic
Programming.

2. Task to be done/ Which logistics used: Write code to implement 0-1 Knapsack using Dynamic
Programming

3. Code:

import java.util.*;

public class Main{


static int knapSack(int W, int wt[], int val[], int n){
int []dp = new int[W + 1];
for (int i = 1; i < n + 1; i++) {
for (int w = W; w >= 0; w--) {
if (wt[i - 1] <= w)
dp[w] = Math.max(dp[w], dp[w - wt[i - 1]] + val[i - 1]);
}
}
return dp[W];
}

public static void main(String[] args){


int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n = val.length;
System.out.print(knapSack(W, wt, val, n));
}
}

Output:

Time Complexity: O(N*W)

Space Complexity: O(W)

4. Learning outcomes (What I have learnt):

1. Understood the concept of dynamic programming.

2. Learnt to solve DP programs using 0-1 knapsack algorithm.

5. Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):

Sr. No. Parameters Marks Obtained Maximum Marks


1.
2.
3.

You might also like