

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum size subset with given sum in C++
Problem statement
Given an array of N elements and sum. We need to find size of maximum size subset whose sum is equal to given sum
Example
If input array is arr = { 2, 3, 5, 10 } and sum = 20 then output will be 4 as −
2 + 3 + 5 + 10 = 20 which is equal to given sum
Algorithm
We can use dynamic programming to solve this problem.
To count the maximal subset, we use another DP array (called as ‘count array’) where count[i][j] is maximal of.
- count[i][j-1]. Here current element is not considered.
- scount[i- X][j-1] + 1. Here X is value of the current element selected for subset.
Example
#include<bits/stdc++.h> using namespace std; int isSubsetSum(int set[], int n, int sum) { bool subset[sum + 1][n + 1]; int count[sum + 1][n + 1]; for (int i = 0; i <= n; i++) { subset[0][i] = true; count[0][i] = 0; } for (int i = 1; i <= sum; i++) { subset[i][0] = false; count[i][0] = -1; } for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; count[i][j] = count[i][j - 1]; if (i >= set[j - 1]) { subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; if (subset[i][j]) { count[i][j] = max(count[i][j - 1], count[i - set[j - 1]][j - 1] + 1); } } } } return count[sum][n]; } int main() { int set[] = { 2, 3, 5, 10 }; int sum = 20; int n = 4; cout<< "Result = " << isSubsetSum(set, n, sum) << endl; }
Output
When you compile and execute above program. It generates following output −
Result = 4
- Related Questions & Answers
- Subset with maximum sum in JavaScript
- Maximum sum two non-overlapping subarrays of given size in C++
- Print maximum sum square sub-matrix of given size in C Program.
- Maximum Size Subarray Sum Equals k in C++
- Minimum partitions of maximum size 2 and sum limited by given value in C++
- Maximum subset with bitwise OR equal to k in C++
- Partition Equal Subset Sum in C++
- Sum of subset differences in C++
- Maximum Subarray Sum in a given Range in C++
- Maximum prefix-sum for a given range in C++
- Find the sum of maximum difference possible from all subset of a given array in Python
- Subset Sum Problem
- C / C++ Program for Subset Sum (Backtracking)
- C++ Largest Subset with Sum of Every Pair as Prime
- Maximum product subset of an array in C++
Advertisements