**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 :

` ````
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

## Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →## Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →## Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →## Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →## Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →## Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →