Double Knapsack | Dynamic Programming
Last Updated :
11 Jul, 2025
Given an array arr[] containing the weight of 'n' distinct items, and two knapsacks that can withstand capactiy1 and capacity2 weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e. an item should be put in one of the bags as a whole.
Examples:
Input: arr[] = [8, 3, 2], capacity1 = 10, capacity2 = 3
Output: 13
Explanation: The first and third items are placed in the first knapsack, while the second item is placed in the second knapsack. This results in a total weight of 13.
Input: arr[] = [8, 5, 3] capacity1 = 10, capacity2 = 3
Output: 11
Explanation: The first item is placed in the first knapsack, and the third item is placed in the second knapsack. This results in a total weight of 11.
Using Recursion– O(2^n) Time and O(n) Space
A recursive solutions is to try out all the possible ways of filling the two knapsacks and choose the one giving the maximum weight.
Every item has 3 choices:
Don't include the current item: If we don't include the current item (i.e., arr[curr]), the maximum weight is simply the same as if we move on to the next item, keeping both knapsack capacities unchanged:
- findMaxWeight(curr, n, arr, capacity1, capacity2) = findMaxWeight(curr+1, n, arr, capacity1, capacity2)
Include the current item in the first knapsack: If the current item can fit into the first knapsack (i.e., arr[curr] ≤ capacity1), then we include it in the first knapsack, reduce the capacity of the first knapsack by arr[curr], and proceed to the next item with updated capacities. The recurrence relation for this choice is:
- findMaxWeight(curr, n, arr, capacity1, capacity2) = max(findMaxWeight(curr+1, n, arr, capacity1-arr[cur], capacity2)+arr[curr], findMaxWeight(curr+1, n, arr, capacity1, capacity2))
Include the current item in the second knapsack: If the current item can fit into the second knapsack (i.e., arr[curr] ≤ capacity2), then we include it in the second knapsack, reduce the capacity of the second knapsack by arr[curr], and proceed to the next item with updated capacities. The recurrence relation for this choice is:
- findMaxWeight(curr, n, arr, capacity1, capacity2) = max(findMaxWeight(curr+1, n, arr, capacity1, capacity2-arr[curr])+arr[curr], findMaxWeight(curr+1, n, arr, capacity1, capacity2))
C++
// C++ program to find the largest subset of
// the array that can fit into two knapsack
// using recursion
#include <iostream>
#include <vector>
using namespace std;
int findMaxWeight(int curr, int n, vector<int> &arr,
int capacity1, int capacity2) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// Option 1: Don't take the current item
int res = findMaxWeight(curr + 1, n, arr,
capacity1, capacity2);
// Option 2: If the current item can be
// added to the first knapsack, do it
if (capacity1 >= arr[curr]) {
int takeInFirst = arr[curr] +
findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2);
res = max(res, takeInFirst);
}
// Option 3: If the current item can be
// added to the second knapsack, do it
if (capacity2 >= arr[curr]) {
int takeInSecond = arr[curr] +
findMaxWeight(curr + 1, n, arr,
capacity1, capacity2 - arr[curr]);
res = max(res, takeInSecond);
}
return res;
}
int maxWeight(vector<int> &arr, int capacity1, int capacity2) {
int n = arr.size();
int res = findMaxWeight(0, n, arr, capacity1, capacity2);
return res;
}
int main() {
vector<int> arr = {8, 2, 3};
int capacity1 = 10, capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
cout << res;
return 0;
}
Java
// Java program to find the largest subset of
// the array that can fit into two knapsacks
// using recursion
import java.util.*;
class GfG {
static int findMaxWeight(int curr, int n, int[] arr,
int capacity1, int capacity2) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// Option 1: Don't take the current item
int res = findMaxWeight(curr + 1, n, arr,
capacity1, capacity2);
// Option 2: If the current item can be
// added to the first knapsack, do it
if (capacity1 >= arr[curr]) {
int takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2);
res = Math.max(res, takeInFirst);
}
// Option 3: If the current item can be
// added to the second knapsack, do it
if (capacity2 >= arr[curr]) {
int takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr]);
res = Math.max(res, takeInSecond);
}
return res;
}
static int maxWeight(int[] arr, int capacity1, int capacity2) {
int n = arr.length;
int res = findMaxWeight(0, n, arr, capacity1, capacity2);
return res;
}
public static void main(String[] args) {
int[] arr = { 8, 2, 3 };
int capacity1 = 10, capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
System.out.println(res);
}
}
Python
# Python program to find the largest subset of
# the array that can fit into two knapsacks
# using recursion
def findMaxWeight(curr, n, arr, capacity1, capacity2):
# Base case: if all items have been considered
if curr >= n:
return 0
# Option 1: Don't take the current item
res = findMaxWeight(curr + 1, n, arr, capacity1, capacity2)
# Option 2: If the current item can be
# added to the first knapsack, do it
if capacity1 >= arr[curr]:
takeInFirst = arr[curr] + \
findMaxWeight(curr + 1, n, arr, capacity1 - arr[curr], capacity2)
res = max(res, takeInFirst)
# Option 3: If the current item can be
# added to the second knapsack, do it
if capacity2 >= arr[curr]:
takeInSecond = arr[curr] + \
findMaxWeight(curr + 1, n, arr, capacity1, capacity2 - arr[curr])
res = max(res, takeInSecond)
return res
def maxWeight(arr, capacity1, capacity2):
n = len(arr)
res = findMaxWeight(0, n, arr, capacity1, capacity2)
return res
if __name__ == "__main__":
arr = [8, 2, 3]
capacity1 = 10
capacity2 = 3
res = maxWeight(arr, capacity1, capacity2)
print(res)
C#
// C# program to find the largest subset of
// the array that can fit into two knapsacks
// using recursion
using System;
class GfG {
static int findMaxWeight(int curr, int n, int[] arr,
int capacity1, int capacity2) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// Option 1: Don't take the current item
int res = findMaxWeight(curr + 1, n, arr,
capacity1, capacity2);
// Option 2: If the current item can be
// added to the first knapsack, do it
if (capacity1 >= arr[curr]) {
int takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2);
res = Math.Max(res, takeInFirst);
}
// Option 3: If the current item can be
// added to the second knapsack, do it
if (capacity2 >= arr[curr]) {
int takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr]);
res = Math.Max(res, takeInSecond);
}
return res;
}
static int maxWeight(int[] arr, int capacity1, int capacity2) {
int n = arr.Length;
int res = findMaxWeight(0, n, arr, capacity1, capacity2);
return res;
}
static void Main(string[] args) {
int[] arr
= { 8, 2, 3 };
int capacity1 = 10, capacity2
= 3;
int res=maxWeight(arr, capacity1, capacity2);
Console.WriteLine(res);
}
}
JavaScript
// JavaScript program to find the largest subset of
// the array that can fit into two knapsacks
// using recursion
function findMaxWeight(curr, n, arr, capacity1, capacity2) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// Option 1: Don't take the current item
let res = findMaxWeight(curr + 1, n, arr,
capacity1, capacity2);
// Option 2: If the current item can be
// added to the first knapsack, do it
if (capacity1 >= arr[curr]) {
let takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2);
res = Math.max(res, takeInFirst);
}
// Option 3: If the current item can be
// added to the second knapsack, do it
if (capacity2 >= arr[curr]) {
let takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr]);
res = Math.max(res, takeInSecond);
}
return res;
}
function maxWeight(arr, capacity1, capacity2) {
let n = arr.length;
let res = findMaxWeight(0, n, arr, capacity1, capacity2);
return res;
}
let arr = [ 8, 2, 3 ];
let capacity1 = 10, capacity2 = 3;
let res = maxWeight(arr, capacity1,capacity2);
console.log(res);
Using Memoization – O(n*capacity1*capacity2) Time and O(n*capacity1*capacity2) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure: The solution to the two-knapsack problem can be derived from the optimal solutions of smaller subproblems. Specifically, for any given n (the number of items considered) and the remaining capacities of the two knapsacks (capacity1 and capacity2), we can express the recursive relation as follows.
2. Overlapping Subproblems: In the recursive solution to the problem of maximizing the weight in two knapsacks, we observe that many subproblems are computed multiple times, which leads to overlapping subproblems.
- We need to track all three parameters, so we create a 3D memoization table of size (n+1) x (capacity1+1) x (capacity2+1).
- This table is initialized with -1 to indicate that no subproblems have been computed yet.
- If the value at memo[curr][capacity1][capacity2] is not -1, return the already computed result to avoid recomputing the same subproblem.
C++
// C++ program to find the largest subset of
// the array that can fit into two knapsack
// using memoization
#include <iostream>
#include <vector>
using namespace std;
int findMaxWeight(int curr, int n, vector<int> &arr, int capacity1,
int capacity2, vector<vector<vector<int>>> &memo) {
// Base case: If all items have been considered,
// return 0 as no more items can be added
if (curr >= n)
return 0;
// If the result for this subproblem is already
// computed, return the memoized value
if (memo[curr][capacity1][capacity2] != -1)
return memo[curr][capacity1][capacity2];
// Option 1: Don't take the current item, and
// proceed to the next item
int res = findMaxWeight(curr + 1, n, arr,
capacity1, capacity2, memo);
// Option 2: If the current item can be added
// to the first knapsack, include it
if (capacity1 >= arr[curr]) {
int takeInFirst = arr[curr] +
findMaxWeight(curr + 1, n, arr, capacity1 - arr[curr],
capacity2, memo);
res = max(res, takeInFirst);
}
// Option 3: If the current item can be added
// to the second knapsack, include it
if (capacity2 >= arr[curr]) {
int takeInSecond = arr[curr] +
findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr], memo);
res = max(res, takeInSecond);
}
return memo[curr][capacity1][capacity2] = res;
}
int maxWeight(vector<int> &arr, int capacity1, int capacity2) {
int n = arr.size();
vector<vector<vector<int>>> memo =
vector<vector<vector<int>>>(n, vector<vector<int>>
(capacity1 + 1, vector<int>(capacity2 + 1, -1)));
int res = findMaxWeight(0, n, arr, capacity1, capacity2, memo);
return res;
}
int main() {
vector<int> arr = {8, 2, 3};
int capacity1 = 10, capacity2 = 3;
int res=maxWeight(arr, capacity1, capacity2);
cout << res;
return 0;
}
Java
// Java program to find the largest subset of
// the array that can fit into two knapsack
// using memoization
import java.util.*;
class GfG {
static int findMaxWeight(int curr, int n, int[] arr,
int capacity1, int capacity2, int[][][] memo) {
// Base case: if all items have been considered
if (curr >= n) {
return 0;
}
// If the result is already computed for this
// subproblem, return it
if (memo[curr][capacity1][capacity2] != -1) {
return memo[curr][capacity1][capacity2];
}
// Option 1: Don't take the current item
int res
= findMaxWeight(curr + 1, n, arr,
capacity1, capacity2, memo);
// Option 2: If the current item can be added
// to the first knapsack, do it
if (capacity1 >= arr[curr]) {
int takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2, memo);
res = Math.max(res, takeInFirst);
}
// Option 3: If the current item can be added to the
// second knapsack, do it
if (capacity2 >= arr[curr]) {
int takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr], memo);
res = Math.max(res, takeInSecond);
}
// Store the result in the memoization table and
// return it
memo[curr][capacity1][capacity2] = res;
return res;
}
static int maxWeight(int[] arr, int capacity1, int capacity2) {
int n = arr.length;
// Create a memoization table with all values
// initialized to -1
int[][][] memo = new int[n][capacity1 + 1][capacity2 + 1];
// Initialize memoization table with -1
for (int i = 0; i < n; i++) {
for (int j = 0; j <= capacity1; j++) {
for (int k = 0; k <= capacity2; k++) {
memo[i][j][k] = -1;
}
}
}
return findMaxWeight(0, n, arr, capacity1, capacity2, memo);
}
public static void main(String[] args) {
int[] arr = { 8, 2, 3 };
int capacity1 = 10, capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
System.out.println(res);
}
}
Python
# Python program to find the largest subset of
# the array that can fit into two knapsack
# using memoization
def findMaxWeight(curr, n, arr, capacity1, capacity2, memo):
# Base case: if all items have been considered
if curr >= n:
return 0
# If the result is already computed for
# this subproblem, return it
if memo[curr][capacity1][capacity2] != -1:
return memo[curr][capacity1][capacity2]
# Option 1: Don't take the current item
res = findMaxWeight(curr + 1, n, arr, capacity1, capacity2, memo)
# Option 2: If the current item can be added
# to the first knapsack, do it
if capacity1 >= arr[curr]:
takeInFirst = arr[curr] + \
findMaxWeight(curr + 1, n, arr, capacity1 - arr[curr], capacity2, memo)
res = max(res, takeInFirst)
# Option 3: If the current item can be added
# to the second knapsack, do it
if capacity2 >= arr[curr]:
takeInSecond = arr[curr] + \
findMaxWeight(curr + 1, n, arr, capacity1, capacity2 - arr[curr], memo)
res = max(res, takeInSecond)
# Store the result in the memoization table and
# return it
memo[curr][capacity1][capacity2] = res
return res
def maxWeight(arr, capacity1, capacity2):
n = len(arr)
# Create a memoization table with all values
# initialized to -1
memo = [[[-1 for _ in range(capacity2 + 1)]
for _ in range(capacity1 + 1)] for _ in range(n)]
return findMaxWeight(0, n, arr, capacity1, capacity2, memo)
if __name__ == "__main__":
arr = [8, 2, 3]
capacity1 = 10
capacity2 = 3
res = maxWeight(arr, capacity1, capacity2)
print(res)
C#
// C# program to find the largest subset of
// the array that can fit into two knapsack
// using memoization
using System;
class GfG {
static int findMaxWeight(int curr, int n, int[] arr,
int capacity1, int capacity2, int[, , ] memo) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// If the result is already computed for this
// subproblem, return it
if (memo[curr, capacity1, capacity2] != -1)
return memo[curr, capacity1, capacity2];
// Option 1: Don't take the current item
int res
= findMaxWeight(curr + 1, n, arr,
capacity1, capacity2, memo);
// Option 2: If the current item can be added to the
// first knapsack, do it
if (capacity1 >= arr[curr]) {
int takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2, memo);
res = Math.Max(res, takeInFirst);
}
// Option 3: If the current item can be added to the
// second knapsack, do it
if (capacity2 >= arr[curr]) {
int takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr], memo);
res = Math.Max(res, takeInSecond);
}
// Store the result in the memoization table and
// return it
memo[curr, capacity1, capacity2] = res;
return res;
}
static int maxWeight(int[] arr, int capacity1, int capacity2) {
int n = arr.Length;
// Create a memoization table with all values
// initialized to -1
int[, , ] memo = new int[n, capacity1 + 1, capacity2 + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= capacity1; j++) {
for (int k = 0; k <= capacity2; k++) {
memo[i, j, k] = -1;
}
}
}
return findMaxWeight(0, n, arr, capacity1, capacity2, memo);
}
static void Main() {
int[] arr = { 8, 2, 3 };
int capacity1 = 10;
int capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
Console.WriteLine(res);
}
}
JavaScript
// JavaScript program to find the largest subset of
// the array that can fit into two knapsack
// using memoization
function findMaxWeight(curr, n, arr, capacity1, capacity2, memo) {
// Base case: if all items have been considered
if (curr >= n)
return 0;
// If the result is already computed for this
// subproblem, return it
if (memo[curr][capacity1][capacity2] !== -1)
return memo[curr][capacity1][capacity2];
// Option 1: Don't take the current item
let res = findMaxWeight(curr + 1, n, arr, capacity1, capacity2, memo);
// Option 2: If the current item can be added to the
// first knapsack, do it
if (capacity1 >= arr[curr]) {
let takeInFirst
= arr[curr]
+ findMaxWeight(curr + 1, n, arr,
capacity1 - arr[curr], capacity2, memo);
res = Math.max(res, takeInFirst);
}
// Option 3: If the current item can be added to the
// second knapsack, do it
if (capacity2 >= arr[curr]) {
let takeInSecond
= arr[curr]
+ findMaxWeight(curr + 1, n, arr, capacity1,
capacity2 - arr[curr], memo);
res = Math.max(res, takeInSecond);
}
// Store the result in the memoization table and return
// it
memo[curr][capacity1][capacity2] = res;
return res;
}
function maxWeight(arr, capacity1, capacity2) {
let n = arr.length;
// Create a memoization table with all values
// initialized to -1
let memo = new Array(n);
for (let i = 0; i < n; i++) {
memo[i] = new Array(capacity1 + 1);
for (let j = 0; j <= capacity1; j++) {
memo[i][j] = new Array(capacity2 + 1).fill(-1);
}
}
return findMaxWeight(0, n, arr, capacity1, capacity2, memo);
}
let arr = [ 8, 2, 3 ];
let capacity1 = 10;
let capacity2 = 3;
let res = maxWeight(arr, capacity1, capacity2);
console.log(res);
Using Tabulation - O(n*capacity1*capacity2) Time and O(n*capacity1*capacity2) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
So we will create 3D array dp of size (n + 1) x (capacity1 + 1) x (capacity2 + 1). Here, dp[i][j][k] represents the maximum weight that can be achieved by considering items from arr[0] to arr[i-1] with two knapsacks of remaining capacities j and k.
Base Case:
If no items are considered (i = 0), then no weight can be placed in either knapsack, so:
dp[0][j][k]=0 for all j, k
Recurrence Relation:
For each item i (1<=i<=n), we have three choices:
- Do not include item arr[i-1] in either knapsack
dp[i][j][k] = dp[i-1][j][k]
- Include item arr[i-1] in the first knapsack if its weight arr[i-1] is less than or equal to j:
dp[i][j][k] = max(dp[i][j][k], arr[i-1] + dp[i-1][j - arr[i-1]][k])
- Include item arr[i-1] in the second knapsack if its weight arr[i-1] is less than or equal to k:
dp[i][j][k] = max(dp[i][j][k], arr[i-1] + dp[i-1][j][k - arr[i-1]])
C++
// C++ program to find the largest subset of
// the array that can fit into two knapsack
// using tabulation
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int maxWeight(vector<int> &arr, int capacity1, int capacity2) {
int n = arr.size();
// Initialize a 3D DP array with dimensions (n+1) x (w1+1) x (w2+1)
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>
(capacity1 + 1, vector<int>(capacity2 + 1, 0)));
// Fill the DP array iteratively
for (int i = 1; i <= n; ++i) {
int weight = arr[i - 1];
for (int j = 0; j <= capacity1; ++j) {
for (int k = 0; k <= capacity2; ++k) {
// Option 1: Don't take the current item
dp[i][j][k] = dp[i - 1][j][k];
// Option 2: Take the current item in the
// first knapsack, if possible
if (j >= weight) {
dp[i][j][k] = max(dp[i][j][k], weight + dp[i - 1][j - weight][k]);
}
// Option 3: Take the current item in the
// second knapsack, if possible
if (k >= weight) {
dp[i][j][k] = max(dp[i][j][k], weight + dp[i - 1][j][k - weight]);
}
}
}
}
return dp[n][capacity1][capacity2];
}
int main() {
vector<int> arr = {8, 2, 3};
int capacity1 = 10, capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
cout << res;
return 0;
}
Java
// Java program to find the largest subset of
// the array that can fit into two knapsack
// using tabulation
import java.util.Arrays;
import java.util.List;
class GfG {
static int maxWeight(List<Integer> arr, int capacity1,
int capacity2) {
int n = arr.size();
// Initialize a 3D DP array with dimensions (n+1) x
// (w1+1) x (w2+1)
int[][][] dp = new int[n + 1][capacity1 + 1][capacity2 + 1];
// Fill the DP array iteratively
for (int i = 1; i <= n; i++) {
int weight = arr.get(i - 1);
for (int j = 0; j <= capacity1; j++) {
for (int k = 0; k <= capacity2; k++) {
// Option 1: Don't take the current item
dp[i][j][k] = dp[i - 1][j][k];
// Option 2: Take the current item in
// the first knapsack, if possible
if (j >= weight) {
dp[i][j][k] = Math.max(
dp[i][j][k],
weight
+ dp[i - 1][j - weight][k]);
}
// Option 3: Take the current item in
// the second knapsack, if possible
if (k >= weight) {
dp[i][j][k] = Math.max(
dp[i][j][k],
weight
+ dp[i - 1][j][k - weight]);
}
}
}
}
return dp[n][capacity1][capacity2];
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(8, 2, 3);
int capacity1 = 10, capacity2 = 3;
int res=maxWeight(arr, capacity1, capacity2);
System.out.println(res);
}
}
Python
# Python program to find the largest subset of
# the array that can fit into two knapsack
# using tabulation
def maxWeight(arr, capacity1, capacity2):
n = len(arr)
# Initialize a 3D DP array with dimensions
# (n+1) x (w1+1) x (w2+1)
dp = [[[0 for _ in range(capacity2 + 1)] for _ in range(capacity1 + 1)]
for _ in range(n + 1)]
# Fill the DP array iteratively
for i in range(1, n + 1):
weight = arr[i - 1]
for j in range(capacity1 + 1):
for k in range(capacity2 + 1):
# Option 1: Don't take the current item
dp[i][j][k] = dp[i - 1][j][k]
# Option 2: Take the current item in the
# first knapsack, if possible
if j >= weight:
dp[i][j][k] = max(dp[i][j][k], weight +
dp[i - 1][j - weight][k])
# Option 3: Take the current item in the
# second knapsack, if possible
if k >= weight:
dp[i][j][k] = max(dp[i][j][k], weight +
dp[i - 1][j][k - weight])
return dp[n][capacity1][capacity2]
arr = [8, 2, 3]
capacity1 = 10
capacity2 = 3
res = maxWeight(arr, capacity1, capacity2)
print(res)
C#
// C# program to find the largest subset of
// the array that can fit into two knapsack
// using tabulation
using System;
using System.Collections.Generic;
class GfG {
static int maxWeight(List<int> arr, int capacity1, int capacity2) {
int n = arr.Count;
// Initialize a 3D DP array with dimensions (n+1) x
// (w1+1) x (w2+1)
int[, , ] dp = new int[n + 1, capacity1 + 1, capacity2 + 1];
// Fill the DP array iteratively
for (int i = 1; i <= n; i++) {
int weight = arr[i - 1];
for (int j = 0; j <= capacity1; j++) {
for (int k = 0; k <= capacity2; k++) {
// Option 1: Don't take the current item
dp[i, j, k] = dp[i - 1, j, k];
// Option 2: Take the current item in
// the first knapsack, if possible
if (j >= weight) {
dp[i, j, k] = Math.Max(
dp[i, j, k],
weight
+ dp[i - 1, j - weight, k]);
}
// Option 3: Take the current item in
// the second knapsack, if possible
if (k >= weight) {
dp[i, j, k] = Math.Max(
dp[i, j, k],
weight
+ dp[i - 1, j, k - weight]);
}
}
}
}
return dp[n, capacity1, capacity2];
}
static void Main() {
List<int> arr = new List<int>{ 8, 2, 3 };
int capacity1 = 10, capacity2 = 3;
int res = maxWeight(arr, capacity1, capacity2);
Console.WriteLine(res);
}
}
JavaScript
// JavaScript program to find the largest subset of
// the array that can fit into two knapsack
// using tabulation
function maxWeight(arr, capacity1, capacity2) {
const n = arr.length;
// Initialize a 3D DP array with dimensions (n+1) x
// (capacity1+1) x (capacity2+1)
const dp = Array.from(
{length : n + 1},
() => Array.from({length : capacity1 + 1},
() => Array(capacity2 + 1).fill(0)));
// Fill the DP array iteratively
for (let i = 1; i <= n; i++) {
const weight = arr[i - 1];
for (let j = 0; j <= capacity1; j++) {
for (let k = 0; k <= capacity2; k++) {
// Option 1: Don't take the current item
dp[i][j][k] = dp[i - 1][j][k];
// Option 2: Take the current item in the
// first knapsack, if possible
if (j >= weight) {
dp[i][j][k] = Math.max(
dp[i][j][k],
weight + dp[i - 1][j - weight][k]);
}
// Option 3: Take the current item in the
// second knapsack, if possible
if (k >= weight) {
dp[i][j][k] = Math.max(
dp[i][j][k],
weight + dp[i - 1][j][k - weight]);
}
}
}
}
return dp[n][capacity1][capacity2];
}
const arr = [ 8, 2, 3 ];
const capacity1 = 10;
const capacity2= 3;
const res = maxWeight(arr, capacity1, capacity2);
console.log(res);
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem