C++ program to choose some numbers for which there will be no subset whose sum is k


Suppose we have two numbers n and k. We have to choose the maximum number of distinct elements from 1 to n, so that no subset whose sum is equal to k. If we can find then return the chosen numbers.

So, if the input is like n = 5; k = 3, then the output will be [4, 5, 2]

Steps

To solve this, we will follow these steps −

for initialize i := (k + 1) / 2, when i <= k - 1, update (increase i by 1), do:
   print i
for initialize i := k + 1, when i <= n, update (increase i by 1), do:
   print i

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(int n, int k) {
   for (int i = (k + 1) / 2; i <= k - 1; i++) {
      cout << i << ", ";
   }
   for (int i = k + 1; i <= n; i++) {
      cout << i << ", ";
   }
}
int main() {
   int n = 5;
   int k = 3;
   solve(n, k);
}

Input

5, 3

Output

2, 4, 5,

Updated on: 03-Mar-2022

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements