Category: subset

Sum of all subsets of a given size

Given an array arr[] consisting of N integers and a positive integer K, the task is to find the sum of all the subsets of size K.Examples:Input: arr[] = {1, 2, 4, 5}, K = 2Output: 36Explanation:The subsets of size K(= 2) are = {1, 2}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {4, […]

Continue Reading

Maximum possible difference of two subsets of an array | Set 2

  #include using namespace std;  int maxSumAfterPartition(int arr[], int n){        vector pos;          vector neg;          int zero = 0;          int pos_sum = 0;          int neg_sum = 0;          for (int i = 0; i < n; i++) {          if (arr[i] > 0) {              pos.push_back(arr[i]);            pos_sum += arr[i];        }        else if (arr[i] < 0) {              neg.push_back(arr[i]);            neg_sum += arr[i];        }        else {              zero++;        }    }          int ans = 0;              sort(pos.begin(), pos.end());              sort(neg.begin(), neg.end(), greater());              if (pos.size() > 0 && neg.size() > 0) […]

Continue Reading

Sum of subsets nearest to K possible from two given arrays

  #include using namespace std;  int ans = INT_MAX;  int mini = INT_MAX;  void findClosestTarget(int i, int curr,                       int B[], int M,                       int K){              if (abs(curr – K) < mini) {                  mini = abs(curr - K);                  ans = curr;    }              if (abs(curr - K) == mini) {                  ans = min(ans, curr);    }          if (i >= M)        return;          findClosestTarget(i + 1, curr + B[i],                      B, M, K);          findClosestTarget(i + 1, curr + 2 * […]

Continue Reading