# 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++) {
}
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])```
```

## 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 .

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

## Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

## Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

## Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty