346 N 5th St Reading Pa - 19601

Given weights and values of n items, put these items in a knapsack of chapters W to go the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-i] and wt[0..n-1] which correspond values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to West. Y'all cannot break an item, either pick the complete item or don't pick it (0-1 belongings).

knapsack-problem

Method one: Recursion by Animate being-Force algorithm OR Exhaustive Search.
Approach: A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset.
Optimal Sub-construction : To consider all subsets of items, at that place can exist 2 cases for every particular.

  1. Case 1: The particular is included in the optimal subset.
  2. Case ii: The item is not included in the optimal gear up.

Therefore, the maximum value that can be obtained from 'n' items is the max of the post-obit two values.

  1. Maximum value obtained by n-1 items and Westward weight (excluding nth item).
  2. Value of nth item plus maximum value obtained past n-1 items and W minus the weight of the nth item (including nth item).

If the weight of 'nth' item is greater than 'W', then the nth detail cannot be included and Instance 1 is the simply possibility.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

int max( int a, int b) { return (a > b) ? a : b; }

int knapSack( int W, int wt[], int val[], int north)

{

if (n == 0 || W == 0)

return 0;

if (wt[n - ane] > Due west)

return knapSack(W, wt, val, north - 1);

else

render max(

val[n - 1]

+ knapSack(W - wt[n - one],

wt, val, due north - 1),

knapSack(W, wt, val, due north - 1));

}

int principal()

{

int val[] = { 60, 100, 120 };

int wt[] = { x, 20, 30 };

int Westward = 50;

int northward = sizeof (val) / sizeof (val[0]);

cout << knapSack(West, wt, val, n);

render 0;

}

C

#include <stdio.h>

int max( int a, int b) { return (a > b) ? a : b; }

int knapSack( int W, int wt[], int val[], int n)

{

if (n == 0 || Due west == 0)

return 0;

if (wt[n - 1] > W)

return knapSack(W, wt, val, n - i);

else

return max(

val[n - 1]

+ knapSack(West - wt[n - 1],

wt, val, n - ane),

knapSack(West, wt, val, due north - 1));

}

int main()

{

int val[] = { lx, 100, 120 };

int wt[] = { 10, 20, 30 };

int Westward = fifty;

int n = sizeof (val) / sizeof (val[0]);

printf ( "%d" , knapSack(W, wt, val, n));

return 0;

}

Java

class Knapsack {

static int max( int a, int b)

{

render (a > b) ? a : b;

}

static int knapSack( int W, int wt[], int val[], int n)

{

if (n == 0 || W == 0 )

render 0 ;

if (wt[n - 1 ] > Westward)

return knapSack(W, wt, val, n - 1 );

else

return max(val[n - 1 ]

+ knapSack(Westward - wt[n - 1 ], wt,

val, due north - ane ),

knapSack(W, wt, val, north - 1 ));

}

public static void main(String args[])

{

int val[] = new int [] { threescore , 100 , 120 };

int wt[] = new int [] { x , twenty , 30 };

int W = 50 ;

int n = val.length;

System.out.println(knapSack(W, wt, val, northward));

}

}

Python

def knapSack(W, wt, val, northward):

if n = = 0 or Westward = = 0 :

return 0

if (wt[north - 1 ] > Due west):

render knapSack(West, wt, val, due north - one )

else :

return max (

val[north - 1 ] + knapSack(

W - wt[n - ane ], wt, val, due north - 1 ),

knapSack(W, wt, val, n - 1 ))

val = [ lx , 100 , 120 ]

wt = [ 10 , 20 , 30 ]

Due west = l

due north = len (val)

impress knapSack(Due west, wt, val, n)

C#

using Organization;

class GFG {

static int max( int a, int b)

{

return (a > b) ? a : b;

}

static int knapSack( int W, int [] wt,

int [] val, int due north)

{

if (northward == 0 || W == 0)

render 0;

if (wt[n - 1] > W)

return knapSack(Due west, wt,

val, north - 1);

else

return max(val[n - one]

+ knapSack(W - wt[north - 1], wt,

val, north - one),

knapSack(West, wt, val, n - one));

}

public static void Main()

{

int [] val = new int [] { 60, 100, 120 };

int [] wt = new int [] { x, 20, thirty };

int Due west = 50;

int northward = val.Length;

Panel.WriteLine(knapSack(Westward, wt, val, n));

}

}

PHP

<?php

function knapSack( $Westward , $wt , $val , $due north )

{

if ( $n == 0 || $W == 0)

return 0;

if ( $wt [ $n - 1] > $Due west )

return knapSack( $Due west , $wt , $val , $northward - 1);

else

return max( $val [ $northward - i] +

knapSack( $W - $wt [ $north - ane],

$wt , $val , $due north - ane),

knapSack( $Westward , $wt , $val , $northward -1));

}

$val = array (threescore, 100, 120);

$wt = assortment (ten, 20, xxx);

$W = 50;

$n = count ( $val );

echo knapSack( $Westward , $wt , $val , $due north );

?>

Javascript

<script>

function max(a, b)

{

return (a > b) ? a : b;

}

role knapSack(W, wt, val, n)

{

if (n == 0 || W == 0)

return 0;

if (wt[n - one] > W)

render knapSack(W, wt, val, n - 1);

else

render max(val[n - i] +

knapSack(W - wt[n - i], wt, val, n - i),

knapSack(W, wt, val, n - 1));

}

let val = [ 60, 100, 120 ];

let wt = [ ten, 20, 30 ];

let Due west = 50;

let due north = val.length;

document.write(knapSack(West, wt, val, northward));

</script>

It should be noted that the to a higher place function computes the aforementioned sub-problems again and again. See the following recursion tree, Thou(1, 1) is beingness evaluated twice. The time complication of this naive recursive solution is exponential (2^n).

In the following recursion tree, K() refers  to knapSack(). The two parameters indicated in the following recursion tree are n and W. The recursion tree is for following sample inputs. wt[] = {i, ane, one}, Westward = 2, val[] = {10, xx, 30}                        K(n, West)                        One thousand(3, two)                      /            \                   /                \                            K(2, 2)                  K(2, i)           /       \                  /    \          /           \              /        \        Thou(i, two)      K(1, 1)        K(one, 1)     K(1, 0)        /  \         /   \              /        \      /      \     /       \          /            \ One thousand(0, 2)  Thou(0, 1)  K(0, i)  G(0, 0)  M(0, ane)   K(0, 0) Recursion tree for Knapsack capacity ii  units and three items of 1 unit of measurement weight.

Complexity Analysis:

  • Fourth dimension Complexity: O(2north).
    As in that location are redundant subproblems.
  • Auxiliary Space :O(1).
    As no extra data structure has been used for storing values.

Since subproblems are evaluated again, this trouble has Overlapping Sub-issues property. And so the 0-1 Knapsack problem has both properties (run across this and this) of a dynamic programming problem.

Method 2: Like other typical Dynamic Programming(DP) problems, re-computation of same subproblems can be avoided by constructing a temporary array Chiliad[][] in bottom-upward manner. Following is Dynamic Programming based implementation.

Approach: In the Dynamic programming we will work because the aforementioned cases as mentioned in the recursive arroyo. In a DP[][] tabular array let'southward consider all the possible weights from '1' to 'W' as the columns and weights that can be kept every bit the rows.
The state DP[i][j] will announce maximum value of 'j-weight' considering all values from '1 to ith'. So if we consider 'wi' (weight in 'ith' row) nosotros tin make full information technology in all columns which take 'weight values > wi'. Now two possibilities tin can take place:

  • Fill up 'wi' in the given column.
  • Exercise not fill 'wi' in the given cavalcade.

At present we have to take a maximum of these two possibilities, formally if we do not fill 'ith' weight in 'jth' cavalcade then DP[i][j] state will be same every bit DP[i-1][j] but if we fill the weight, DP[i][j] will be equal to the value of 'wi'+ value of the column weighing 'j-wi' in the previous row. So we take the maximum of these two possibilities to fill the current state. This visualisation volition make the concept clear:

Let weight elements = {1, 2, 3} Let weight values = {10, 15, forty} Capacity=6     0   i   2   three   4   five   6  0  0   0   0   0   0   0   0  1  0  10  ten  10  10  10  10  2  0  10  15  25  25  25  25  three  0          Explanation:          For filling 'weight = 2' we come up  across 'j = 3' in which  we take maximum of  (10, 15 + DP[i][3-2]) = 25      |        | 'two'       'ii filled' not filled       0   ane   2   iii   4   5   6  0  0   0   0   0   0   0   0  1  0  10  x  x  10  10  10  2  0  10  15  25  25  25  25  3  0  ten  15  40  50  55  65          Caption:          For filling 'weight=three',  we run across 'j=iv' in which  we accept maximum of (25, twoscore + DP[two][4-3])  = 50  For filling 'weight=iii'  nosotros come across 'j=5' in which  we take maximum of (25, 40 + DP[2][5-3]) = 55  For filling 'weight=3'  nosotros come across 'j=6' in which  we accept maximum of (25, 40 + DP[2][6-3]) = 65

C++

#include <bits/stdc++.h>

using namespace std;

int max( int a, int b)

{

return (a > b) ? a : b;

}

int knapSack( int West, int wt[], int val[], int n)

{

int i, w;

vector<vector< int >> 1000(due north + ane, vector< int >(West + ane));

for (i = 0; i <= n; i++)

{

for (w = 0; w <= W; w++)

{

if (i == 0 || w == 0)

M[i][w] = 0;

else if (wt[i - 1] <= westward)

Grand[i][due west] = max(val[i - 1] +

K[i - 1][w - wt[i - 1]],

Grand[i - 1][w]);

else

K[i][west] = K[i - one][w];

}

}

render Thousand[n][West];

}

int primary()

{

int val[] = { 60, 100, 120 };

int wt[] = { x, 20, thirty };

int W = 50;

int n = sizeof (val) / sizeof (val[0]);

cout << knapSack(W, wt, val, due north);

render 0;

}

C

#include <stdio.h>

int max( int a, int b)

{

return (a > b) ? a : b;

}

int knapSack( int W, int wt[], int val[], int n)

{

int i, w;

int Grand[n + 1][Due west + 1];

for (i = 0; i <= n; i++)

{

for (w = 0; w <= W; w++)

{

if (i == 0 || westward == 0)

K[i][w] = 0;

else if (wt[i - 1] <= w)

K[i][w] = max(val[i - one]

+ K[i - i][w - wt[i - ane]],

K[i - one][westward]);

else

K[i][w] = K[i - one][w];

}

}

return K[n][Westward];

}

int master()

{

int val[] = { 60, 100, 120 };

int wt[] = { 10, xx, 30 };

int West = 50;

int n = sizeof (val) / sizeof (val[0]);

printf ( "%d" , knapSack(W, wt, val, n));

render 0;

}

Java

course Knapsack {

static int max( int a, int b)

{

return (a > b) ? a : b;

}

static int knapSack( int W, int wt[],

int val[], int n)

{

int i, w;

int G[][] = new int [n + i ][Due west + ane ];

for (i = 0 ; i <= n; i++)

{

for (w = 0 ; w <= W; w++)

{

if (i == 0 || west == 0 )

M[i][w] = 0 ;

else if (wt[i - ane ] <= due west)

K[i][w]

= max(val[i - one ]

+ M[i - i ][w - wt[i - 1 ]],

K[i - ane ][w]);

else

K[i][w] = One thousand[i - one ][due west];

}

}

render K[northward][W];

}

public static void main(Cord args[])

{

int val[] = new int [] { 60 , 100 , 120 };

int wt[] = new int [] { 10 , 20 , 30 };

int W = 50 ;

int north = val.length;

System.out.println(knapSack(W, wt, val, n));

}

}

Python

def knapSack(Due west, wt, val, n):

One thousand = [[ 0 for x in range (W + 1 )] for x in range (n + ane )]

for i in range (n + one ):

for westward in range (W + ane ):

if i = = 0 or due west = = 0 :

K[i][w] = 0

elif wt[i - 1 ] < = w:

K[i][west] = max (val[i - i ]

+ M[i - ane ][west - wt[i - i ]],

K[i - ane ][w])

else :

1000[i][w] = Yard[i - 1 ][w]

return K[north][W]

val = [ 60 , 100 , 120 ]

wt = [ 10 , 20 , 30 ]

W = 50

due north = len (val)

impress (knapSack(W, wt, val, north))

C#

using System;

class GFG {

static int max( int a, int b)

{

render (a > b) ? a : b;

}

static int knapSack( int W, int [] wt,

int [] val, int n)

{

int i, westward;

int [, ] Thousand = new int [n + i, W + ane];

for (i = 0; i <= n; i++)

{

for (w = 0; w <= West; westward++)

{

if (i == 0 || w == 0)

M[i, w] = 0;

else if (wt[i - 1] <= w)

K[i, w] = Math.Max(

val[i - 1]

+ K[i - 1, west - wt[i - 1]],

K[i - 1, w]);

else

G[i, w] = 1000[i - 1, w];

}

}

return K[north, Westward];

}

static void Main()

{

int [] val = new int [] { 60, 100, 120 };

int [] wt = new int [] { x, 20, xxx };

int Due west = 50;

int n = val.Length;

Console.WriteLine(knapSack(W, wt, val, n));

}

}

PHP

<?php

office knapSack( $Due west , $wt , $val , $n )

{

$Yard = array ( array ());

for ( $i = 0; $i <= $n ; $i ++)

{

for ( $w = 0; $w <= $Westward ; $w ++)

{

if ( $i == 0 || $west == 0)

$K [ $i ][ $w ] = 0;

else if ( $wt [ $i - one] <= $w )

$Thousand [ $i ][ $w ] = max( $val [ $i - i] +

$Thou [ $i - one][ $due west -

$wt [ $i - 1]],

$One thousand [ $i - i][ $w ]);

else

$Thou [ $i ][ $w ] = $K [ $i - 1][ $due west ];

}

}

return $Thou [ $n ][ $W ];

}

$val = array (60, 100, 120);

$wt = array (10, 20, xxx);

$W = l;

$due north = count ( $val );

echo knapSack( $W , $wt , $val , $n );

?>

Javascript

<script>

function max(a, b)

{

render (a > b) ? a : b;

}

function knapSack(Due west, wt, val, n)

{

let i, w;

permit K = new Assortment(northward + ane);

for (i = 0; i <= n; i++)

{

Yard[i] = new Assortment(W + 1);

for (w = 0; w <= W; due west++)

{

if (i == 0 || w == 0)

M[i][w] = 0;

else if (wt[i - 1] <= west)

Chiliad[i][west]

= max(val[i - 1]

+ Thou[i - 1][w - wt[i - 1]],

M[i - 1][w]);

else

G[i][w] = K[i - 1][westward];

}

}

return G[n][W];

}

let val = [ 60, 100, 120 ];

let wt = [ ten, 20, 30 ];

allow W = 50;

allow north = val.length;

document.write(knapSack(Due west, wt, val, north));

</script>

Complexity Analysis:

  • Fourth dimension Complexity: O(N*Westward).
    where 'N' is the number of weight element and 'West' is capacity. As for every weight element we traverse through all weight capacities i<=w<=West.
  • Auxiliary Space: O(North*Westward).
    The utilise of 2-D array of size 'N*W'.

Scope for Improvement :-We used the same approach but with optimized infinite complexity

C++

#include <bits/stdc++.h>

using namespace std;

int knapSack( int W, int wt[], int val[], int n)

{

int i, due west;

int Yard[2][West + 1];

for (i = 0; i <= northward; i++) {

for (w = 0; w <= W; westward++) {

if (i == 0 || due west == 0)

One thousand[i % 2][w] = 0;

else if (wt[i - 1] <= w)

K[i % 2][west] = max(

val[i - 1]

+ G[(i - 1) % 2][west - wt[i - 1]],

1000[(i - 1) % two][w]);

else

K[i % ii][w] = K[(i - 1) % two][w];

}

}

render Thousand[n % two][Westward];

}

int main()

{

int val[] = { sixty, 100, 120 };

int wt[] = { 10, xx, 30 };

int W = 50;

int n = sizeof (val) / sizeof (val[0]);

cout << knapSack(W, wt, val, n);

return 0;

}

Coffee

import coffee.util.*;

course GFG {

static int knapSack( int Westward, int wt[], int val[], int n)

{

int i, w;

int [][]1000 = new int [ 2 ][West + i ];

for (i = 0 ; i <= n; i++) {

for (w = 0 ; w <= W; w++) {

if (i == 0 || westward == 0 )

G[i % 2 ][westward] = 0 ;

else if (wt[i - 1 ] <= due west)

K[i % 2 ][westward] = Math.max(

val[i - 1 ]

+ K[(i - ane ) % two ][due west - wt[i - 1 ]],

K[(i - 1 ) % 2 ][w]);

else

Grand[i % ii ][w] = Thou[(i - ane ) % two ][w];

}

}

render K[n % 2 ][Due west];

}

public static void main(Cord[] args)

{

int val[] = { lx , 100 , 120 };

int wt[] = { 10 , xx , 30 };

int W = 50 ;

int north = val.length;

Arrangement.out.print(knapSack(W, wt, val, northward));

}

}

Python3

def knapSack(Westward, wt, val, n):

Thou = [[ 0 for x in range (Due west + 1 )] for y in range ( 2 )]

for i in range (n + one ):

for w in range (W + i ):

if (i = = 0 or w = = 0 ):

Yard[i % ii ][west] = 0

elif (wt[i - i ] < = w):

K[i % 2 ][w] = max (

val[i - 1 ]

+ Chiliad[(i - one ) % 2 ][w - wt[i - 1 ]],

K[(i - 1 ) % 2 ][w])

else :

K[i % 2 ][west] = 1000[(i - ane ) % ii ][w]

render K[n % ii ][Westward]

if __name__ = = "__main__" :

val = [ 60 , 100 , 120 ]

wt = [ ten , 20 , 30 ]

Due west = 50

n = len (val)

impress (knapSack(W, wt, val, n))

C#

using System;

public class GFG {

static int knapSack( int W, int []wt, int []val, int due north) {

int i, due west;

int [,] K = new int [2,W + 1];

for (i = 0; i <= n; i++) {

for (w = 0; w <= W; westward++) {

if (i == 0 || w == 0)

K[i % 2, w] = 0;

else if (wt[i - 1] <= westward)

M[i % 2,w] = Math.Max(val[i - 1] + K[(i - 1) % 2,w - wt[i - 1]], K[(i - 1) % 2,w]);

else

K[i % ii,west] = K[(i - 1) % 2,w];

}

}

return 1000[northward % ii,W];

}

public static void Main(String[] args) {

int []val = { 60, 100, 120 };

int []wt = { 10, 20, 30 };

int W = 50;

int n = val.Length;

Console.Write(knapSack(W, wt, val, north));

}

}

Javascript

<script>

function knapSack(W , wt , val , n) {

var i, due west;

var Yard = Array(2).fill().map(()=>Assortment(W + ane).fill(0));

for (i = 0; i <= northward; i++) {

for (w = 0; due west <= West; west++) {

if (i == 0 || w == 0)

K[i % two][w] = 0;

else if (wt[i - ane] <= w)

Chiliad[i % 2][w] = Math.max(val[i - 1] +

Grand[(i - i) % 2][w - wt[i - ane]],

1000[(i - 1) % 2][due west]);

else

Thou[i % 2][w] = K[(i - 1) % 2][w];

}

}

return K[n % 2][W];

}

var val = [ sixty, 100, 120 ];

var wt = [ 10, xx, xxx ];

var W = 50;

var n = val.length;

document.write(knapSack(W, wt, val, n));

</script>

Complexity Assay:

  • Time Complication: O(Northward*W).
  • Auxiliary Space: O(2*W)
    Equally we are using a 2-D assortment but with just 2 rows.

Method 3: This method uses Memoization Technique (an extension of recursive approach).
This method is basically an extension to the recursive approach and so that we can overcome the problem of computing redundant cases and thus increased complication. Nosotros tin solve this problem by simply creating a ii-D array that can store a detail country (n, west) if we go it the get-go fourth dimension. At present if we come across the aforementioned land (northward, w) once again instead of calculating information technology in exponential complexity we can directly render its issue stored in the table in constant time. This method gives an border over the recursive approach in this attribute.

C++

#include <$.25/stdc++.h>

using namespace std;

int knapSackRec( int Due west, int wt[],

int val[], int i,

int ** dp)

{

if (i < 0)

return 0;

if (dp[i][Westward] != -1)

return dp[i][Due west];

if (wt[i] > Westward) {

dp[i][Due west] = knapSackRec(Due west, wt,

val, i - ane,

dp);

render dp[i][Due west];

}

else {

dp[i][W] = max(val[i]

+ knapSackRec(Due west - wt[i],

wt, val,

i - 1, dp),

knapSackRec(W, wt, val,

i - ane, dp));

render dp[i][W];

}

}

int knapSack( int W, int wt[], int val[], int due north)

{

int ** dp;

dp = new int *[n];

for ( int i = 0; i < n; i++)

dp[i] = new int [W + 1];

for ( int i = 0; i < n; i++)

for ( int j = 0; j < W + 1; j++)

dp[i][j] = -1;

return knapSackRec(W, wt, val, northward - 1, dp);

}

int main()

{

int val[] = { threescore, 100, 120 };

int wt[] = { 10, 20, 30 };

int W = 50;

int north = sizeof (val) / sizeof (val[0]);

cout << knapSack(W, wt, val, northward);

render 0;

}

Java

grade GFG{

static int max( int a, int b)

{

render (a > b) ? a : b;

}

static int knapSackRec( int West, int wt[],

int val[], int n,

int [][]dp)

{

if (northward == 0 || W == 0 )

return 0 ;

if (dp[north][W] != - ane )

render dp[n][Due west];

if (wt[due north - 1 ] > West)

return dp[due north][W] = knapSackRec(Due west, wt, val,

n - ane , dp);

else

return dp[northward][Westward] = max((val[north - i ] +

knapSackRec(W - wt[n - i ], wt,

val, northward - 1 , dp)),

knapSackRec(W, wt, val,

n - one , dp));

}

static int knapSack( int W, int wt[], int val[], int N)

{

int dp[][] = new int [N + 1 ][Westward + 1 ];

for ( int i = 0 ; i < Due north + 1 ; i++)

for ( int j = 0 ; j < W + 1 ; j++)

dp[i][j] = - 1 ;

return knapSackRec(W, wt, val, N, dp);

}

public static void principal(String [] args)

{

int val[] = { lx , 100 , 120 };

int wt[] = { x , twenty , 30 };

int W = 50 ;

int N = val.length;

System.out.println(knapSack(Due west, wt, val, N));

}

}

Python3

val = [ lx , 100 , 120 ]

wt = [ 10 , 20 , 30 ]

W = 50

n = len (val)

t = [[ - 1 for i in range (Due west + 1 )] for j in range (n + ane )]

def knapsack(wt, val, Due west, n):

if n = = 0 or W = = 0 :

return 0

if t[n][W] ! = - ane :

return t[n][Westward]

if wt[n - 1 ] < = West:

t[northward][W] = max (

val[n - 1 ] + knapsack(

wt, val, W - wt[due north - 1 ], due north - one ),

knapsack(wt, val, W, n - 1 ))

return t[north][Westward]

elif wt[n - ane ] > W:

t[due north][Due west] = knapsack(wt, val, Due west, due north - 1 )

return t[due north][W]

impress (knapsack(wt, val, W, n))

C#

using Organization;

public form GFG

{

static int max( int a, int b) { return (a > b) ? a : b; }

static int knapSackRec( int W, int [] wt, int [] val,

int n, int [, ] dp)

{

if (n == 0 || W == 0)

return 0;

if (dp[n, W] != -1)

return dp[n, W];

if (wt[north - one] > W)

return dp[n, West]

= knapSackRec(W, wt, val, north - 1, dp);

else

return dp[n, W]

= max((val[due north - ane]

+ knapSackRec(W - wt[north - ane], wt, val,

northward - 1, dp)),

knapSackRec(West, wt, val, north - one, dp));

}

static int knapSack( int W, int [] wt, int [] val, int N)

{

int [, ] dp = new int [Northward + ane, Due west + i];

for ( int i = 0; i < Due north + 1; i++)

for ( int j = 0; j < W + 1; j++)

dp[i, j] = -one;

render knapSackRec(W, wt, val, N, dp);

}

static public void Main()

{

int [] val = new int []{ lx, 100, 120 };

int [] wt = new int []{ 10, 20, thirty };

int W = 50;

int N = val.Length;

Panel.WriteLine(knapSack(Due west, wt, val, N));

}

}

Javascript

<script>

office max(a,  b)

{

return (a > b) ? a : b;

}

function knapSackRec(West, wt, val, n,dp)

{

if (due north == 0 || W == 0)

render 0;

if (dp[n][W] != -1)

return dp[n][W];

if (wt[n - 1] > W)

return dp[n][W] = knapSackRec(Due west, wt, val,

n - 1, dp);

else

render dp[n][W] = max((val[north - 1] +

knapSackRec(W - wt[northward - 1], wt,

val, n - 1, dp)),

knapSackRec(W, wt, val,

n - 1, dp));

}

function knapSack( Due west, wt,val,N)

{

var dp = new Array(Due north + one);

for ( var i = 0; i < dp.length; i++)

{

dp[i]= new Array(W + i);

}

for ( var i = 0; i < Northward + one; i++)

for ( var j = 0; j < W + 1; j++)

dp[i][j] = -1;

return knapSackRec(W, wt, val, Northward, dp);

}

var val= [ 60, 100, 120 ];

var wt = [ ten, twenty, 30 ];

var W = 50;

var Northward = val.length;

document.write(knapSack(W, wt, val, Northward));

</script>

Complication Analysis:

  • Time Complexity: O(N*Due west).
    Every bit redundant calculations of states are avoided.
  • Auxiliary Space: O(Northward*West).
    The use of 2D assortment data structure for storing intermediate states-:

[Annotation: For 32bit integer apply long instead of int.]
References:

  • http://www.es.ele.tue.nl/teaching/5MC10/Solutions/knapsack.pdf
  • http://www.cse.unl.edu/~goddard/Courses/CSCE310J/Lectures/Lecture8-DynamicProgramming.pdf
  • https://youtu.be/T4bY72lCQac?list=PLqM7alHXFySGMu2CSdW_6d2u1o6WFTIO-

Please write comments if you find anything incorrect, or you want to share more information nearly the topic discussed above.

Method four :- Again we utilise the dynamic programming approach with even more optimized space complexity .

C++

#include <bits/stdc++.h>

using namespace std;

int knapSack( int W, int wt[], int val[], int due north)

{

int dp[W + 1];

memset (dp, 0, sizeof (dp));

for ( int i = 1; i < n + 1; i++) {

for ( int w = West; w >= 0; due west--) {

if (wt[i - 1] <= w)

dp[west] = max(dp[w],

dp[westward - wt[i - 1]] + val[i - one]);

}

}

render dp[W];

}

int chief()

{

int val[] = { 60, 100, 120 };

int wt[] = { ten, 20, xxx };

int W = 50;

int north = sizeof (val) / sizeof (val[0]);

cout << knapSack(W, wt, val, n);

return 0;

}

Java

import java.util.*;

class GFG{

static int knapSack( int West, int wt[], int val[], int due north)

{

int []dp = new int [W + 1 ];

for ( int i = 1 ; i < n + 1 ; i++) {

for ( int w = Due west; w >= 0 ; due west--) {

if (wt[i - 1 ] <= west)

dp[w] = Math.max(dp[w],

dp[w - wt[i - 1 ]] + val[i - 1 ]);

}

}

return dp[Westward];

}

public static void main(Cord[] args)

{

int val[] = { sixty , 100 , 120 };

int wt[] = { 10 , twenty , 30 };

int W = 50 ;

int due north = val.length;

Organisation.out.print(knapSack(W, wt, val, n));

}

}

Python3

def knapSack(West, wt, val, n):

dp = [ 0 for i in range (West + 1 )]

for i in range ( 1 , n + ane ):

for due west in range (W, 0 , - 1 ):

if wt[i - ane ] < = westward:

dp[westward] = max (dp[west], dp[west - wt[i - 1 ]] + val[i - i ])

return dp[W]

val = [ 60 , 100 , 120 ]

wt = [ 10 , xx , 30 ]

W = fifty

n = len (val)

print (knapSack(W, wt, val, n))

C#

using Organization;

public class GFG {

static int knapSack( int W, int []wt, int []val, int n)

{

int [] dp = new int [W + i];

for ( int i = ane; i < n + 1; i++)

{

for ( int w = W; w >= 0; w--)

{

if (wt[i - 1] <= w)

dp[westward] = Math.Max(dp[w], dp[due west - wt[i - 1]] + val[i - one]);

}

}

return dp[Due west];

}

public static void Main(String[] args) {

int []val = { 60, 100, 120 };

int []wt = { 10, 20, 30 };

int W = l;

int northward = val.Length;

Console.Write(knapSack(W, wt, val, due north));

}

}

Javascript

<script>

function knapSack(Due west , wt , val , n)

{

var dp = Array(Due west + 1).fill(0);

for (i = one; i < n + ane; i++) {

for (w = West; w >= 0; w--) {

if (wt[i - 1] <= w)

dp[west] = Math.max(dp[w], dp[w - wt[i - 1]] + val[i - 1]);

}

}

return dp[W];

}

var val = [ 60, 100, 120 ];

var wt = [ ten, 20, 30 ];

var W = 50;

var n = val.length;

document.write(knapSack(Westward, wt, val, n));

</script>

Complexity Analysis:

Time Complexity: O(N*W). As redundant calculations of states are avoided.

Auxiliary Space: O(W) As nosotros are using 1-D array instead of two-D array.


goodwinbispecephe.blogspot.com

Source: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/

0 Response to "346 N 5th St Reading Pa - 19601"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel