Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int arr[] = {5, 10, 7, 6, 4, 20}, n = 6, target = 25;
- int knapsack(int indx, int sum) {
- if(sum > target) {
- return sum;
- }
- if(indx == n) {
- if(sum <= target) {
- return INT_MAX;
- }
- return sum;
- }
- int ret1 = knapsack(indx + 1, sum + arr[indx]);
- int ret2 = knapsack(indx + 1, sum);
- return min(ret1, ret2);
- }
- int main() {
- sort(arr, arr +n); // if the array isn't already sorted
- cout << knapsack(0, 0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment