Knapsack


Problem Statement :


Given an array of integers and a target sum, determine the sum nearest to but not exceeding the target that can be created. To create the sum, use any element of your array zero or more times.

For example, if arr = [2,3,4] and your target sum is 10, you might select [2,2,2,2,2], [2,2,3,3] or [3,3,31]. In this case, you can arrive at exactly the target.

Function Description

Complete the unboundedKnapsack function in the editor below. It must return an integer that represents the sum nearest to without exceeding the target value.

unboundedKnapsack has the following parameter(s):

k: an integer
arr: an array of integers
Input Format

The first line contains an integer t, the number of test cases.

Each of the next t pairs of lines are as follows:
- The first line contains two integers n and k, the length of arr and the target sum.
- The second line contains n space separated integers arr[i].

Constraints

1 <= t <= 10
1 <= n,k,arr[i] <= 2000

Output Format

Print the maximum sum for each test case which is as near as possible, but not exceeding, to the target sum on a separate line.



Solution :



title-img


                            Solution in C :

In C++ :





#include <bits/stdc++.h>
using namespace std;
int dp[2005]; 
int main() {
    int a; cin >> a;
    for (int g=0;g<a; g++)
        {memset(dp,0,sizeof(dp)); 
        int b,c; cin >> b >> c; vector <int> t;
        for (int y=0;y<b; y++){int d; cin >> d;t.push_back(d);}
        dp[0]=1; int r=0; 
        for (int g=1; g<=c; g++)
            {
            for (int y=0;y<t.size(); y++)
                {
                if (t[y]>g) continue; if (dp[g-t[y]]) dp[g]=1; 
            }
            if (dp[g]) r=g; 
        }
        cout << r << '\n'; 
    }
    return 0;
}








In Java :





import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

public class Solution {

	private static Scanner sc;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int i = 0; i < T; i++) {
			int n = sc.nextInt();
			int k = sc.nextInt();
			HashSet<Integer> map = new HashSet<Integer>();
			for (int j = 0; j < n; j++) {
				map.add(sc.nextInt());
			}
			System.out.println(getMultSum(map, k));
		}
	}

	private static int getMultSum(HashSet<Integer> map, int k) {
		Iterator<Integer> it = map.iterator();
		boolean[] sum = new boolean[k + 1];
		Arrays.fill(sum, false);
		sum[0] = true;
		int a = 0;
		for (int i = 0; i <= k; i++) {

			if (sum[i] == true) {
				it = map.iterator();
				while (it.hasNext()) {
					a = it.next();
					if ((i + a) <= k)
						sum[i + a] = true;
				}
			}
		}
		for(int i=k;i>=0;i--){
			if(sum[i] == true){
				return i;
			}
		}
		return 0;
	}
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

struct qnode
    {
    int data;
    struct qnode*next;
    
};

struct queue
    {
   struct qnode*front,*rear;
     
};

struct qnode*newnode(int k)
    {
    struct qnode*temp=(struct qnode*)malloc(sizeof(struct qnode));
    temp->data=k;
    temp->next=NULL;
    return temp;
    
};

struct queue*createque()
    {
    struct queue*q=(struct queue*)malloc(sizeof(struct queue));
    q->front=q->rear=NULL;
    return q;
};

void enqueue(struct queue*q,int k)
    {
    struct qnode*temp=newnode(k);
    if(q->front==NULL)
        {
        q->front =q->rear=temp;
    }
    else
        {
        q->rear->next=temp;
        q->rear=temp;
        
    }
}

int dequeue(struct queue*q)
    {
    if(q->front==NULL)
        return -1;
    int temp=q->front->data;
    q->front=q->front->next;
    if(q->front==NULL)
        q->rear=NULL;
    return temp;
    
}
    




int main() {

    int t;
    int n,k;
    int res,i,temp,temp2;
    int arr2[2003];int j,num;
    int *arr;
    int found,found1;
    scanf("%d",&t);
    while(t--)
        {
        for(i=0;i<2003;++i)
            arr2[i]=0;
        found=0;
        scanf("%d%d",&n,&k);
        temp=res=k;
        arr=(int*)malloc(n*sizeof(int));
        j=0;
        found1=0;
        for(i=0;i<n;++i)
        {
           
            
            scanf("%d",&num);
            if(k%num==0)
             {   found1=1;
              found=1;}   
            if(arr2[num]==0)
                {
                arr2[num]=1;
                arr[j]=num;
                j++;
            }
        }
        
        
        struct queue*q=createque();
        enqueue(q,k);
        while(((temp2=dequeue(q))!=-1) && found==0)
            {
           // printf("temp2=%d",temp2);
            for(i=0;i<j;++i)
                {
                temp=temp2-arr[i];
                
                if(temp<0)
                    continue;
                if(res>temp)
                    res=temp;
                
                if(res==0)
                {
                    found=1;
                    break;
                }
                else
                    enqueue(q,temp);
    
            }
        }
        
        if(found&&found1)
            printf("%d\n",k);
        
        else if(res==k)
            printf("0\n");
        else
        printf("%d\n",k-res);
            
        
        
        
    }
    
    return 0;
}








In Python3 :





t=int(input())
for _ in range(t):
    lst=[int(i) for i in input().split()]
    goal=lst[1]
    nums=[int(i) for i in input().split()]
    dyno=[0]
    dyno += [-1]*goal
    for i in range(len(dyno)):
        tmp=-1
        largest_x=-1
        val=0
        for x in nums:
            if i-x >= 0 and dyno[i-x]+x>=val:
                tmp=i-x
                largest_x=x
                val=dyno[i-x]+x
        if tmp<0:
            dyno[i]=0
        else:
            dyno[i]=largest_x+dyno[tmp]

    print(dyno[-1])
                        








View More Similar Problems

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →