0% found this document useful (0 votes)
19 views3 pages

Experiment 8

Uploaded by

Arvind Khoda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views3 pages

Experiment 8

Uploaded by

Arvind Khoda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment-8

Aim:- 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,3,1] .

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

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.

Sample Input

2
3 12
169
59
34448

Code:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int unboundedKnapsack(int k, vector<int>& arr) {


vector<int> dp(k + 1, 0);

for (int i = 1; i <= k; i++) {


for (int j = 0; j < arr.size(); j++) {
if (arr[j] <= i) {
dp[i] = max(dp[i], dp[i - arr[j]] + arr[j]);
}
}
}

return dp[k];
}

int main() {
// Input values
int t;
cin >> t;

while (t--) {
int n, k;
cin >> n >> k;

vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Call the unboundedKnapsack function


int result = unboundedKnapsack(k, arr);

// Output the result


cout << "Maximum sum: " << result << endl;
}

return 0;
}

Output:

You might also like