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

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →