Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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,
Advertisements
