The Wayback Machine - https://web.archive.org/web/20240909135503/https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/
Open In App

Unbounded Knapsack (Repetition of items allowed)

Last Updated : 25 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item.

Note: N is always positive i.e greater than zero

Examples: 

Input : W = 100 val[] = {1, 30} wt[] = {1, 50}
Output : 100
There are many ways to fill knapsack.
1) 2 instances of 50 unit weight item.
2) 100 instances of 1 unit weight item.
3) 1 instance of 50 unit weight item and 50 instances of 1 unit weight items.
We get maximum value with option 2.

Input : W = 8 val[] = {10, 40, 50, 70} wt[] = {1, 3, 4, 5}
Output : 110
We get maximum value with one unit of weight 5 and one unit of weight 3.

Recursive 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-structure: To consider all subsets of items, there can be two cases for every item.

Case 1: The item is included in the optimal subset. We do not reduce the number of items in the recursive calls in this case. This is where it differs from bounded knapsack.
Case 2: The item is not included in the optimal set.
Therefore, the maximum value that can be obtained from ‘n’ items is the max of the following two values.

Maximum value obtained by n-1 items and W weight (excluding nth item).
Value of nth item plus maximum value obtained by n(because of infinite supply) 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 item cannot be included and Case 1 is the only possibility.

Below is the implementation of the above approach: 

C++
#include <bits/stdc++.h>
using namespace std;

// Returns the maximum value that
// can be put in a knapsack of capacity W
int uksRec(int W, vector<int>& wt, 
           vector<int>& val, int idx) {
  
    // Base Case
    if (idx == 0) {
        return (W / wt[0]) * val[0];
    }

    // There are two cases: either take
    // the element or not.
    int notTake = uksRec(W, wt, val, idx - 1);

    // if take then weight = W-wt[idx] and
    // index will remain same.
    int take = INT_MIN;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx);
    }

    return max(take, notTake);
}

// Wrapper method for unbounded knapsack
int uks(int W, vector<int>& wt, vector<int>& val) {
    int n = val.size();
    return uksRec(W, wt, val, n - 1);
}

// Driver code
int main() {
    int W = 100;
    vector<int> val = {10, 30, 20};
    vector<int> wt = {5, 10, 15};

    cout << uks(W, wt, val);
    return 0;
}
C
#include <stdio.h>
#include <limits.h>

// Recursive function for the unbounded
// knapsack problem
int uksRec(int W, int wt[], int val[], int idx) {
  
    // Base Case
    if (idx == 0) {
        return (W / wt[0]) * val[0];
    }

    // There are two cases: either take the 
    // element or not.
    int notTake = uksRec(W, wt, val, idx - 1);

    // if take then weight = W-wt[idx] and
    // index will remain same. 
    int take = INT_MIN;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx);
    }

    return take > notTake ? take : notTake;
}

// Wrapper function for unbounded knapsack
int uks(int W, int wt[], int val[], int n) {
    return uksRec(W, wt, val, n - 1);
}

// Driver code
int main() {
    int W = 100;
    int val[] = { 10, 30, 20 };
    int wt[] = { 5, 10, 15 };
    int n = sizeof(val) / sizeof(val[0]);

    printf("%d\n", uks(W, wt, val, n));
    return 0;
}
Java
import java.util.*;

public class GfG {

    // Recursive function for the unbounded
    // knapsack problem
    static int uksRec(int W, int[] wt, 
                      int[] val, int idx) {
        
        // Base Case
        if (idx == 0) {
            return (W / wt[0]) * val[0];
        }

        // There are two cases: either take 
        // the element or not.
        int notTake = uksRec(W, wt, val, idx - 1);

        // if take then weight = W-wt[idx] and 
        // index will remain same. 
        int take = Integer.MIN_VALUE;
        if (wt[idx] <= W) {
            take = val[idx] + uksRec(W - wt[idx], wt, val, idx);
        }

        return Math.max(take, notTake);
    }

    // Wrapper method for unbounded knapsack
    static int uks(int W, int[] wt, int[] val) {
        int n = val.length;
        return uksRec(W, wt, val, n - 1);
    }

    // Driver code
    public static void main(String[] args) {
        int W = 100;
        int[] val = {10, 30, 20};
        int[] wt = {5, 10, 15};

        System.out.println(uks(W, wt, val));
    }
}
Python
def uks_rec(W, wt, val, idx):
  
    # Base Case
    if idx == 0:
        return (W // wt[0]) * val[0]

    # There are two cases: either take the 
    # element or not.
    not_take = uks_rec(W, wt, val, idx - 1)

    # if take then weight = W-wt[idx] and 
    # index will remain same.  
    take = float('-inf')
    if wt[idx] <= W:
        take = val[idx] + uks_rec(W - wt[idx], wt, val, idx)

    return max(take, not_take)

# Wrapper method for unbounded knapsack
def uks(W, wt, val):
    n = len(val)
    return uks_rec(W, wt, val, n - 1)

# Driver code
W = 100
val = [10, 30, 20]
wt = [5, 10, 15]

print(uks(W, wt, val))
C#
using System;

class GfG
{
    // Recursive function for the unbounded
    // knapsack problem
    static int UksRec(int W, int[] wt,
                      int[] val, int idx)
    {
        // Base Case
        if (idx == 0)
        {
            return (W / wt[0]) * val[0];
        }

       // There are two cases: either take 
       // the element or not.
        int notTake = UksRec(W, wt, val, idx - 1);

       // if take then weight = W-wt[idx] and 
       // index will remain same.
        int take = int.MinValue;
        if (wt[idx] <= W)
        {
            take = val[idx] + UksRec(W - wt[idx], wt, val, idx);
        }

        return Math.Max(take, notTake);
    }

    // Wrapper method for unbounded knapsack
    static int Uks(int W, int[] wt, int[] val)
    {
        int n = val.Length;
        return UksRec(W, wt, val, n - 1);
    }

    // Driver code
    static void Main()
    {
        int W = 100;
        int[] val = { 10, 30, 20 };
        int[] wt = { 5, 10, 15 };

        Console.WriteLine(Uks(W, wt, val));
    }
}
JavaScript
function uksRec(W, wt, val, idx) {

    // Base Case
    if (idx === 0) {
        return Math.floor(W / wt[0]) * val[0];
    }

    // There are two cases: either take
    // the element or not.
    const notTake = uksRec(W, wt, val, idx - 1);
   
    // if take then weight = W-wt[idx] and 
    // index will remain same.
    let take = Number.MIN_SAFE_INTEGER;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx);
    }

    return Math.max(take, notTake);
}

// Wrapper method for unbounded knapsack
function uks(W, wt, val) {
    const n = val.length;
    return uksRec(W, wt, val, n - 1);
}

// Driver code
const W = 100;
const val = [10, 30, 20];
const wt = [5, 10, 15];

console.log(uks(W, wt, val));

Output
300

Time complexity: O(2^n) where n is the number of items.
Space complexity: O(W*n) as we are using a 2D array to store the results.

Memoization – O(nW) time and O(nW) space

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

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function for the unbounded knapsack problem
int uksRec(int W, vector<int>& wt, vector<int>& val, int idx, 
                               vector<vector<int>>& memo) {

    // Base Case
    if (idx == 0) {
        return (W / wt[0]) * val[0];
    }
  
    // If the value is already calculated, return the previous value
    if (memo[idx][W] != -1)
        return memo[idx][W];
    
    // There are two cases: either take the element or not.
    int notTake = uksRec(W, wt, val, idx - 1, memo);

    int take = INT_MIN;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx, memo);
    }
    
    return memo[idx][W] = max(take, notTake);
}

// Wrapper method for unbounded knapsack
int uks(int W, vector<int>& wt, vector<int>& val) {
    int n = val.size();
    vector<vector<int>> memo(n, vector<int>(W + 1, -1));
    return uksRec(W, wt, val, n - 1, memo);
}

// Driver code
int main() {
    int W = 100;
    vector<int> val = {10, 30, 20};
    vector<int> wt = {5, 10, 15};

    cout << uks(W, wt, val);
    return 0;
}
C
#include <stdio.h>
#include <limits.h>

#define MAX 101

// Recursive function for the unbounded knapsack problem
int uksRec(int W, int wt[], int val[], int idx, int memo[][MAX]) {

    // Base Case
    if (idx == 0) {
        return (W / wt[0]) * val[0];
    }
    // If the value is already calculated, return the previous value
    if (memo[idx][W] != -1)
        return memo[idx][W];
    
    // There are two cases: either take the element or not.
    int notTake = uksRec(W, wt, val, idx - 1, memo);

    int take = INT_MIN;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx, memo);
    }
    
    return memo[idx][W] = take > notTake ? take : notTake;
}

// Wrapper function for unbounded knapsack
int uks(int W, int wt[], int val[], int n) {
    int memo[MAX][MAX];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= W; j++) {
            memo[i][j] = -1;
        }
    }
    return uksRec(W, wt, val, n - 1, memo);
}

// Driver code
int main() {
    int W = 100;
    int val[] = {10, 30, 20};
    int wt[] = {5, 10, 15};
    int n = sizeof(val) / sizeof(val[0]);

    printf("%d\n", uks(W, wt, val, n));
    return 0;
}
Java
import java.util.Arrays;

public class GfG {

    // Recursive function for the unbounded knapsack problem
    static int uksRec(int W, int[] wt, int[] val, int idx, int[][] memo) {
        
        // Base Case
        if (idx == 0) {
            return (W / wt[0]) * val[0];
        }

        // If the value is already calculated, return the previous value
        if (memo[idx][W] != -1)
            return memo[idx][W];

        // There are two cases: either take the element or not.
        int notTake = uksRec(W, wt, val, idx - 1, memo);

        int take = Integer.MIN_VALUE;
        if (wt[idx] <= W) {
            take = val[idx] + uksRec(W - wt[idx], wt, val, idx, memo);
        }

        return memo[idx][W] = Math.max(take, notTake);
    }

    // Wrapper method for unbounded knapsack
    static int uks(int W, int[] wt, int[] val) {
        int n = val.length;
        int[][] memo = new int[n][W + 1];
        for (int i = 0; i < n; i++) {
            Arrays.fill(memo[i], -1);
        }
        return uksRec(W, wt, val, n - 1, memo);
    }

    // Driver code
    public static void main(String[] args) {
        int W = 100;
        int[] val = {10, 30, 20};
        int[] wt = {5, 10, 15};

        System.out.println(uks(W, wt, val));
    }
}
Python
def uks_rec(W, wt, val, idx, memo):
    # Base Case
    if idx == 0:
        return (W // wt[0]) * val[0]

    # If the value is already calculated, return the previous value
    if memo[idx][W] != -1:
        return memo[idx][W]

    # There are two cases: either take the element or not.
    not_take = uks_rec(W, wt, val, idx - 1, memo)

    take = float('-inf')
    if wt[idx] <= W:
        take = val[idx] + uks_rec(W - wt[idx], wt, val, idx, memo)

    memo[idx][W] = max(take, not_take)
    return memo[idx][W]

# Wrapper method for unbounded knapsack
def uks(W, wt, val):
    n = len(val)
    memo = [[-1 for _ in range(W + 1)] for _ in range(n)]
    return uks_rec(W, wt, val, n - 1, memo)

# Driver code
W = 100
val = [10, 30, 20]
wt = [5, 10, 15]

print(uks(W, wt, val))
C#
using System;

class GfG
{
    // Recursive function for the unbounded knapsack problem
    static int UksRec(int W, int[] wt, int[] val, int idx, int[,] memo)
    {
        // Base Case
        if (idx == 0)
        {
            return (W / wt[0]) * val[0];
        }

        // If the value is already calculated, return the previous value
        if (memo[idx, W] != -1)
        {
            return memo[idx, W];
        }

        // There are two cases: either take the element or not.
        int notTake = UksRec(W, wt, val, idx - 1, memo);

        int take = int.MinValue;
        if (wt[idx] <= W)
        {
            take = val[idx] + UksRec(W - wt[idx], wt, val, idx, memo);
        }

        memo[idx, W] = Math.Max(take, notTake);
        return memo[idx, W];
    }

    // Wrapper method for unbounded knapsack
    static int Uks(int W, int[] wt, int[] val)
    {
        int n = val.Length;
        int[,] memo = new int[n, W + 1];

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j <= W; j++)
            {
                memo[i, j] = -1;
            }
        }

        return UksRec(W, wt, val, n - 1, memo);
    }

    // Driver code
    static void Main()
    {
        int W = 100;
        int[] val = { 10, 30, 20 };
        int[] wt = { 5, 10, 15 };

        Console.WriteLine(Uks(W, wt, val));
    }
}
JavaScript
function uksRec(W, wt, val, idx, memo) {
    // Base Case
    if (idx === 0) {
        return Math.floor(W / wt[0]) * val[0];
    }

    // If the value is already calculated, return the previous value
    if (memo[idx][W] !== -1) {
        return memo[idx][W];
    }

    // There are two cases: either take the element or not.
    const notTake = uksRec(W, wt, val, idx - 1, memo);

    let take = Number.MIN_SAFE_INTEGER;
    if (wt[idx] <= W) {
        take = val[idx] + uksRec(W - wt[idx], wt, val, idx, memo);
    }

    memo[idx][W] = Math.max(take, notTake);
    return memo[idx][W];
}

// Wrapper method for unbounded knapsack
function uks(W, wt, val) {
    const n = val.length;
    const memo = Array.from({ length: n }, () => Array(W + 1).fill(-1));
    return uksRec(W, wt, val, n - 1, memo);
}

// Driver code
const W = 100;
const val = [10, 30, 20];
const wt = [5, 10, 15];

console.log(uks(W, wt, val));

Output
300

Time Complexity: O(n*W)
Auxiliary Space: O(n*W) 

Dynamic Programming – – O(nW) time and O(nW) space

Its an unbounded knapsack problem as we can use 1 or more instances of any resource. A simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which can achieved using all items and i capacity of knapsack. Note that we use 1D array here which is different from classical knapsack where we used 2D array. Here number of items never changes. We always have all items available.
We can recursively compute dp[] using below formula

dp[i] = 0
dp[i] = max(dp[i], dp[i-wt[j]] + val[j] 
                   where j varies from 0 
                   to n-1 such that:
                   wt[j] <= i
result = d[W]

Below is the implementation of above idea. 

C++
#include <bits/stdc++.h>
using namespace std;

// Returns the maximum value with knapsack of W capacity
int uks(int W, vector<int>& val, vector<int>& wt) {
    vector<int> memo(W + 1, 0);

    // Fill memo[] using the recursive formula
    for (int i = 0; i <= W; i++) {
        for (int j = 0; j < val.size(); j++) {
            if (wt[j] <= i) {
                memo[i] = max(memo[i], memo[i - wt[j]] + val[j]);
            }
        }
    }

    return memo[W];
}

// Driver program
int main() {
    int W = 100;
    vector<int> val = {10, 30, 20};
    vector<int> wt = {5, 10, 15};

    cout << uks(W, val, wt);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Returns the maximum value with knapsack 
// of W capacity
int uks(int W, int n, int val[], int wt[]) {
    int memo[W + 1];
    memset(memo, 0, (W + 1) * sizeof(int));

    // Fill memo[] using the recursive formula
    for (int i = 0; i <= W; i++) {
        for (int j = 0; j < n; j++) {
            if (wt[j] <= i) {
                if (memo[i] < memo[i - wt[j]] + val[j]) {
                    memo[i] = memo[i - wt[j]] + val[j];
                }
            }
        }
    }

    return memo[W];
}

// Driver program
int main() {
    int W = 100;
    int val[] = {10, 30, 20};
    int wt[] = {5, 10, 15};
    int n = sizeof(val) / sizeof(val[0]);

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

    return 0;
}
Java
// Java program to find maximum achievable
// value with a knapsack of weight W and
// multiple instances allowed.
public class UboundedKnapsack 
{
    
    private static int max(int i, int j) 
    {
            return (i > j) ? i : j;
    }
    
    // Returns the maximum value with knapsack
    // of W capacity
    private static int unboundedKnapsack(int W, int n, 
                                int[] val, int[] wt) 
    {
        
        // dp[i] is going to store maximum value
        // with knapsack capacity i.
        int dp[] = new int[W + 1];
        
        // Fill dp[] using above recursive formula
        for(int i = 0; i <= W; i++){
            for(int j = 0; j < n; j++){
                if(wt[j] <= i){
                    dp[i] = max(dp[i], dp[i - wt[j]] + 
                                val[j]);
                }
            }
        }
        return dp[W];
    }

    // Driver program
    public static void main(String[] args) 
    {
        int W = 100;
        int val[] = {10, 30, 20};
        int wt[] = {5, 10, 15};
        int n = val.length;
        System.out.println(unboundedKnapsack(W, n, val, wt));
    }
}
// This code is contributed by Aditya Kumar 
Python
 
# Python3 program to find maximum
# achievable value with a knapsack
# of weight W and multiple instances allowed.

# Returns the maximum value 
# with knapsack of W capacity
def unboundedKnapsack(W, n, val, wt):

    # dp[i] is going to store maximum 
    # value with knapsack capacity i.
    dp = [0 for i in range(W + 1)]

    ans = 0

    # Fill dp[] using above recursive formula
    for i in range(W + 1):
        for j in range(n):
            if (wt[j] <= i):
                dp[i] = max(dp[i], dp[i - wt[j]] + val[j])

    return dp[W]

# Driver program
W = 100
val = [10, 30, 20]
wt = [5, 10, 15]
n = len(val)

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

# This code is contributed by Anant Agarwal.
C#
// C# program to find maximum achievable
// value with a knapsack of weight W and
// multiple instances allowed.
using System;

class UboundedKnapsack {
    
    private static int max(int i, int j)
    {
            return (i > j) ? i : j;
    }
    
    // Returns the maximum value 
    // with knapsack of W capacity
    private static int unboundedKnapsack(int W, int n, 
                                  int []val, int []wt) 
    {
        
        // dp[i] is going to store maximum value
        // with knapsack capacity i.
        int []dp = new int[W + 1];
        
        // Fill dp[] using above recursive formula
        for(int i = 0; i <= W; i++){
            for(int j = 0; j < n; j++){
                if(wt[j] <= i){
                    dp[i] = Math.Max(dp[i], dp[i - 
                                        wt[j]] + val[j]);
                }
            }
        }
        return dp[W];
    }

    // Driver program
    public static void Main() 
    {
        int W = 100;
        int []val = {10, 30, 20};
        int []wt = {5, 10, 15};
        int n = val.Length;
        Console.WriteLine(unboundedKnapsack(W, n, val, wt));
    }
}

// This code is contributed by vt_m.
JavaScript
<script>
    // Javascript program to find maximum achievable
    // value with a knapsack of weight W and
    // multiple instances allowed.
    
    function max(i, j)
    {
            return (i > j) ? i : j;
    }
     
    // Returns the maximum value
    // with knapsack of W capacity
    function unboundedKnapsack(W, n, val, wt)
    {
         
        // dp[i] is going to store maximum value
        // with knapsack capacity i.
        let dp = new Array(W + 1);
        dp.fill(0);
         
        // Fill dp[] using above recursive formula
        for(let i = 0; i <= W; i++){
            for(let j = 0; j < n; j++){
                if(wt[j] <= i){
                    dp[i] = Math.max(dp[i], dp[i - wt[j]] + val[j]);
                }
            }
        }
        return dp[W];
    }
    
    let W = 100;
    let val = [10, 30, 20];
    let wt = [5, 10, 15];
    let n = val.length;
    document.write(unboundedKnapsack(W, n, val, wt));
    
</script>
PHP
<?php
// PHP program to find maximum 
// achievable value with a 
// knapsack of weight W and 
// multiple instances allowed.

// Returns the maximum value 
// with knapsack of W capacity
function unboundedKnapsack($W, $n, 
                           $val, $wt)
{
    // dp[i] is going to store 
    // maximum value with 
    // knapsack capacity i.
    for($i = 0; $i <= $W; $i++)
        $dp[$i] = 0;

    $ans = 0;
    
    // Fill dp[] using above
    // recursive formula
    for ($i = 0; $i <= $W; $i++)
    for ($j = 0; $j < $n; $j++)
        if ($wt[$j] <= $i)
            $dp[$i] = max($dp[$i], 
                          $dp[$i - $wt[$j]] + 
                                   $val[$j]);

    return $dp[$W];
}

// Driver Code
$W = 100;
$val = array(10, 30, 20);
$wt = array(5, 10, 15);
$n = count($val); //sizeof($val)/sizeof($val[0]);

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

// This code is contributed
// by shiv_bhakt
?>

Output
300

Time Complexity: O(nW) where W is the total weight(capacity) and N is the total number of items.
Auxiliary Space: O(W) where W is the total weight.


 



Previous Article
Next Article

Similar Reads

Unbounded Knapsack (Repetition of items allowed) | Efficient Approach
Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explanation: The maximum value
8 min read
Unbounded Fractional Knapsack
Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Output: 244.444 Input: val[] = {100, 60, 120}, wt[]
5 min read
Unbounded Knapsack in Python
Given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, the task is to determine the maximum value that can be obtained by putting items into the knapsack. In the Unbounded Knapsack problem, you can use each item as many times as you want. Example: Input: Weights: [1, 3, 4, 5], Values: [10, 40, 50, 70],
2 min read
Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in half
Given weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does not exceed the given capacity W. Examples: Input: W
15+ min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Difference Between Greedy Knapsack and 0/1 Knapsack Algorithms
The 0/1 Knapsack algorithm is a dynamic programming approach where items are either completely included or not at all. It considers all combinations to find the maximum total value. On the other hand, the Greedy Knapsack algorithm, also known as the Fractional Knapsack, allows for items to be broken into fractions, selecting items with the highest
9 min read
Reorder an Array according to given indices with repetition allowed
Given two integer arrays arr and index of size N, the task is to create a new array by inserting the elements given in the arr array at the indices given by the index array. If a particular position occur multiple time then right shift the right-side array elements and then insert element at given index. Note: It is given that all the indices that
6 min read
Ways to sum to N using array elements with repetition allowed
Given a set of m distinct positive integers and a value 'N'. The problem is to count the total number of ways we can form 'N' by doing sum of the array elements. Repetitions and different arrangements are allowed. Examples : Input: arr = {1, 5, 6}, N = 7Output: 6Explanation: The different ways are:1+1+1+1+1+1+11+1+51+5+15+1+11+66+1 Input: arr = {12
6 min read
Printing Items in 0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the items such t
12 min read
POTD Solutions | 25 Oct’ 23 | Knapsack with Duplicate Items
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills. We recommend you to try this
9 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Largest area in a grid unbounded by towers
Given two integers L and W representing the dimensions of a grid, and two arrays X[] and Y[] of length N denoting the number of towers present on the grid at positions (X[i], Y[i]), where (0 &lt;= i &lt;= N - 1). The task is to find the largest unbounded area in the field which is not defended by the towers. Examples: Input: L = 15, W = 8, N = 3 X[
8 min read
Get maximum items when other items of total cost of an item are free
Given a list of prices of 'N' items. A person can buy only one item of any price and he can get other items for free such that the total price of the rest of the items doesn't exceed the price of the bought item. The task is to find the maximum number of items the person can have. Examples: Input: n = 5, arr = {5, 3, 1, 5, 6} Output: 3 The person c
6 min read
Probability of distributing M items among X bags such that first bag contains N items
Given three integers N, M, X. The task is to find the probability of distributing M items among X bags such that first bag contains N items Examples: Input : M = 7, X =3, N = 3 Output : 0.2 The Number of ways to keep 7 items in 3 bags is [Tex]6\choose 2 [/Tex]. The Number of ways to keep 4 items in 2 bags is [Tex]3\choose 1 [/Tex]. As the first bag
5 min read
Distributing items when a person cannot take more than two items of same type
Given N sweets, which can be of many different types, and k customers, one customer won’t make the same type of sweet more than 2 pieces, the task is to find if it is possible to distribute all, then print "Yes" or otherwise "No".Given an array, arr[] represents an array of sweets. arr[i] is type of sweet. Examples: Input : arr[] = {1, 1, 2, 3, 1},
8 min read
Arrangements of N and M items of two types when max X and Y items of each can be consecutive
Given 4 numbers N, M, X, Y. which represent N numbers for the first item and M numbers for the second item, the task is to find the number of arrangements of N + M items together such that not more than X first items and not more than Y second items are placed successively. Examples: Input: N = 2, M = 1, X = 1, Y = 10Output: 1Explanation: Let's mar
15+ min read
Print all permutations with repetition of characters
Given a string of length n, print all permutations of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order Examples: Input: ABOutput:All permutations of AB with repetition are:AAABBABB Input: ABCOutput: All permutations of ABC with repetition are:AAAAABAACABA......CCBCCC For an input stri
10 min read
Longest chain of arr[i], arr[arr[i]], .. without repetition
Given an array of size n such that elements in array are distinct and in range from 0 to n-1. We need to find out length of the longest chain {arr[i], arr[arr[i]], arr[arr[arr[i]]]......} such that no set element repeats. Examples: Input : arr[] = [5, 4, 0, 3, 1, 6, 2] Output :4 Explanation: The longest chain without repetition is {arr[0], arr[5],
7 min read
K length words that can be formed from given characters without repetition
Given an integer k and a string str consisting of lowercase English alphabets, the task is to count how many k-character words (with or without meaning) can be formed from the characters of str when repetition is not allowed. Examples: Input: str = "cat", k = 3 Output: 6 Required words are "cat", "cta", "act", "atc", "tca" and "tac". Input: str = "
6 min read
Print all the permutations of a string without repetition using Collections in Java
Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output. Examples: Input: str = "aa" Output: aa Note that "aa" will be printed only once as duplicates are not all
2 min read
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition
Given a number N, the task is to find the number of ways in which the integer N can be represented as a sum of Fibonacci numbers without repetition of any Fibonacci number. Examples: Input: N = 13Output: 3Explanation: The possible ways to select N as 13 are: {13} {8, 5} {8, 3, 2}. Note that it is not possible to select {5 + 5 + 3} because 5 appears
10 min read
Smallest subarray which upon repetition gives the original array
Given an array arr[] of N integers, the task is to find the smallest subarray brr[] of size at least 2 such that by performing repeating operation on the array brr[] gives the original array arr[]. Print "-1" if it is not possible to find such a subarray. A repeating operation on an array is to append all the current element of the array to the sam
8 min read
Lexicographically largest array possible from first N natural numbers such that every repetition is present at distance equal to its value from its previous occurrence
Given a positive integer N, the task is to construct the lexicographically largest array of size (2 * N - 1) comprising of first N natural numbers such that each element occurs twice except 1 and the repetition of X is exactly X distance apart in the constructed array. Examples: Input: N = 4Output: 4 2 3 2 4 3 1Explanation:For the generated array {
10 min read
Minimize the count of characters to be added or removed to make String repetition of same substring
Given a string S consisting of N characters, the task is to modify the string S by performing the minimum number of following operations such that the modified string S is the concatenation of its half. Insert any new character at any index in the string.Remove any character from the string S.Replace any character with any other character in the st
15+ min read
Check whether given sequence of moves is circular upon infinite repetition
Given a string str denoting a sequence of moves. The task is to check if the moves are repeated an infinite number of times then the movements will be bound in a circular path or not. The movements can be of following types: "G": go straight 1 unit;"L": turn 90 degrees to the left;"R": turn 90 degrees to the right. Examples: Input: str = "GGLLGG"Ou
7 min read
Count of Derangements of given Array with Repetition
Given an array arr[] of N numbers (N ≤ 20), the task is to find the number of Derangements of the array where array elements can be repeated. A derangement is a permutation of N elements, such that no element appears in its original position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0}. Examples: Input: arr[] = {0, 0, 1}Output: 0Expl
13 min read
Convert to a string that is repetition of a substring of k length
Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters. Examples: Input: str = "bdac", k = 2 Output: True We can either replace "bd" with "
7 min read
Distributing all balls without repetition
Given N balls. For convenience, we denote the color of each ball as — lowercase letters. We have to distribute N balls among K people. They will be upset if they get two balls of the same color. We can give any number of balls to people and they won't be upset even if they do not get any balls, but, we have to distribute all the balls, such that no
6 min read
Fractional Knapsack Queries
Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Examples: Input: arr[] = { {1, 2}, {1, 3}, {3, 7} }, q =
9 min read
Knapsack with large Weights
Given a knapsack with capacity C and two arrays w[] and val[] representing the weights and values of N distinct items, the task is to find the maximum value you can put into the knapsack. Items cannot be broken and an item with weight X takes X capacity of the knapsack. Examples: Input: w[] = {3, 4, 5}, val[] = {30, 50, 60}, C = 8 Output: 90 We tak
13 min read