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
AND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution →Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →Castle on the Grid
You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):
View Solution →Down to Zero II
You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.
View Solution →Truck Tour
Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr
View Solution →