Skip to main content

Zero One Knapsack | Recursion

 1. You are given a number n, representing the count of items.

2. You are given n numbers, representing the values of n items.

3. You are given n numbers, representing the weights of n items.

3. You are given a number "cap", which is the capacity of a bag you've.

4. You are required to calculate and print the maximum value that can be created in the bag without 

     overflowing it's capacity.

Note: Each item can be taken 0 or 1 number of times. You are not allowed to put the same item again and again.

Input Format

A number n

v1 v2 .. n number of elements

w1 w2 .. n number of elements

A number cap

Output Format

A number representing the maximum value that can be created in the bag without overflowing it's capacity

Constraints

1 <= n <= 20

0 <= v1, v2, .. n elements <= 50

0 < w1, w2, .. n elements <= 10

0 < cap <= 10

Sample Input

5

15 14 10 45 30

2 5 1 3 4

7

Sample Output

75


Solution:

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int wt[] = new int[n], val[] = new int[n];
        for(int i=0;i<n;i++)
            val[i] = sc.nextInt();
        for(int i=0;i<n;i++)
            wt[i] = sc.nextInt();
        int cap = sc.nextInt();
        
        System.out.println(knapsack(0,n,val,wt,cap));
    }
    
    public static int knapsack(int i,int n,int val[],int wt[],int cap){
        if(i>=n || cap<=0) 
            return 0;
        int taken = 0;
        if(cap-wt[i]>=0)
            taken = knapsack(i+1,n,val,wt,cap-wt[i]) + val[i];
        int notTaken = knapsack(i+1,n,val,wt,cap);
        
        return Math.max(taken, notTaken);
    }
}

Comments

Must Read:

Min Cost In Maze Traversal

1. You are given a number n, representing the number of rows. 2. You are given a number m, representing the number of columns. 3. You are given n*m numbers, representing elements of 2d array a, which represents a maze. 4. You are standing in top-left cell and are required to move to bottom-right cell. 5. You are allowed to move 1 cell right (h move) or 1 cell down (v move) in 1 motion. 6. Each cell has a value that will have to be paid to enter that cell (even for the top-left and bottom-       right cell). 7. You are required to traverse through the matrix and print the cost of path which is least costly. Input Format A number n A number m e11 e12.. e21 e22.. .. n * m number of elements Output Format The cost of least costly path. Constraints 1 <= n <= 10^2 1 <= m <= 10^2 0 <= e1, e2, .. n * m elements <= 1000 Sample Input 6 6 0 1 4 2 8 2 4 3 6 5 0 4 1 2 4 1 4 6 2 0 7 3 2 2 3 1 5 9 2 4 2 7 0 8 5 1 Sample Output 23 Solution: import java.io.*; import...

Programming using Java Hands On - Control Structures | Bill Generation

Bill Generation Tom went to a movie with his friends in a multiplex theatre and during break time he bought pizzas, puffs and cool drinks.  Consider   the following prices :  Rs.100/pizza Rs.20/puffs Rs.10/cooldrink Generate a bill for What Tom has bought. Sample Input 1: Enter the no of pizzas bought:10 Enter the no of puffs bought:12 Enter the no of cool drinks bought:5 Sample Output 1: Bill Details No of pizzas:10 No of puffs:12 No of cooldrinks:5 Total price=1290 ENJOY THE SHOW!!! Result Description Summary of tests *Note: All the test cases might not have same weightage +------------------------------+ | 6 tests run/ 6 tests passed | +------------------------------+

Software Engineering Concepts Configuration Management And Version Control Post-Quiz

 Software Engineering Concepts       Configuration Management And Version Control            Post-Quiz

RDBMS Data Definition Language | Change the name of the table Sales Info

  RDBMS  Data Definition Language  Change the name of the table Sales Info Write an SQL statement to rename the table Sales Info to Sales_Information. (Hint: use alter command to rename the table name) Evaluation Result: Result Description Summary of tests +------------------------------+ | 1 tests run / 1 test passed | +------------------------------+

Zig Zag Pattern

  /* @ToDo     Zig Zag Pattern         *               *                *       *       *       *        *               *               *        */ #include   <iostream> using   namespace   std ; int   main (){       #ifndef  ONLINE_JUDGE          freopen ( "../asset/input.txt" , "r" , stdin );          freopen (...

Reverse a Number

  /* @ToDo     Reverse a Number    7325 => 5237    12345 => 54321 */ #include   <iostream> using   namespace   std ; int   main (){       #ifndef  ONLINE_JUDGE          freopen ( "../asset/input.txt" , "r" , stdin );          freopen ( "../asset/output.txt" , "w" , stdout );     #endif     // Code here!!      int   n ;  cin >> n ;      int   num  =  0 ;      while ( n > 0 ){          num  = ( num * 10 ) + ( n % 10 );          n  /=  10 ;     }       cout << nu...

Knights Tour

1. You are given a number n, the size of a chess board. 2. You are given a row and a column, as a starting point for a knight piece. 3. You are required to generate the all moves of a knight starting in (row, col) such that knight visits       all cells of the board exactly once. 4. Complete the body of printKnightsTour function - without changing signature - to calculate and       print all configurations of the chess board representing the route      of knight through the chess board. Use sample input and output to get more idea. Note -> When moving from (r, c) to the possible 8 options give first precedence to (r - 2, c + 1) and                 move in clockwise manner to                explore other options. Input Format A number n A number row A number col Output Format All configurations of the chess board representing route of knights thro...

Bubble Sort

1. You are given an array(arr) of integers. 2. You have to sort the given array in increasing order using bubble sort. Input Format An Integer n  arr1 arr2.. n integers Output Format Check the sample ouput and question video. Constraints 1 <= N <= 10000 -10^9 <= arr[i] <= 10^9 Sample Input 5 7  -2  4  1  3 Sample Output Comparing -2 and 7 Swapping -2 and 7 Comparing 4 and 7 Swapping 4 and 7 Comparing 1 and 7 Swapping 1 and 7 Comparing 3 and 7 Swapping 3 and 7 Comparing 4 and -2 Comparing 1 and 4 Swapping 1 and 4 Comparing 3 and 4 Swapping 3 and 4 Comparing 1 and -2 Comparing 3 and 1 Comparing 1 and -2 -2 1 3 4 7 Solution: import java.io.*; import java.util.*; public class Main {   public static void bubbleSort(int[] arr) {     //write your code here     for(int i=0;i<arr.length;i++){         for(int j=1;j<arr.length-i;j++)             if(isSmaller(arr,j,j-1)){   ...

Subscribe to Get's Answer by Email