Advertisement
Farid_Mia59

laegest subset1

Nov 16th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. // A Dynamic Programming solution for subset
  2. // sum problem+ maximal subset value.
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Returns size of maximum sized subset
  7. // if there is a subset of set[] with sun
  8. // equal to given sum. It returns -1 if there
  9. // is no subset with given sum.
  10. int isSubsetSum(int set[], int n, int sum)
  11. {
  12. // The value of subset[i][j] will be true if there
  13. // is a subset of set[0..j-1] with sum equal to i
  14. bool subset[sum + 1][n + 1];
  15. int count[sum + 1][n + 1];
  16.  
  17. // If sum is 0, then answer is true
  18. for (int i = 0; i <= n; i++)
  19. {
  20. subset[0][i] = true;
  21. count[0][i] = 0;
  22. }
  23.  
  24. // If sum is not 0 and set is empty,
  25. // then answer is false
  26. for (int i = 1; i <= sum; i++)
  27. {
  28. subset[i][0] = false;
  29. count[i][0] = -1;
  30. }
  31.  
  32. // Fill the subset table in bottom up manner
  33. for (int i = 1; i <= sum; i++)
  34. {
  35. for (int j = 1; j <= n; j++)
  36. {
  37. subset[i][j] = subset[i][j - 1];
  38. count[i][j] = count[i][j - 1];
  39. if (i >= set[j - 1])
  40. {
  41. subset[i][j] = subset[i][j] ||
  42. subset[i - set[j - 1]][j - 1];
  43.  
  44. if (subset[i][j])
  45. count[i][j] = max(count[i][j - 1],
  46. count[i - set[j - 1]][j - 1] + 1);
  47. }
  48. }
  49. }
  50.  
  51. return count[sum][n];
  52. }
  53.  
  54. // Driver code
  55. int main()
  56. {
  57. int set[] = { 1,2, 3,4, 5,6,7 };
  58. int sum = 20;
  59. int n = 7;
  60. cout<< isSubsetSum(set, n, sum);
  61. }
  62.  
  63. // This code is contributed by DrRoot_
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement