Given two positive integers N and K such that K≤N, the task is to find the maximum number of distinct integers in the range [1, N] having no subset with a sum equal to K. If there are multiple solutions, print any.
Examples:
Input: N = 5, K = 3
Output: 1 4 5
Explanation: There are two sets of distinct numbers of size 3 which don’t have any subset sum of 3.
These are {1, 4, 5} and {2, 4, 5}. So, print any of them in any order.Input: N = 1, K =1
Output: 0
Approach: The idea is based on the following observations:
- Any number greater than K can be chosen as they can never contribute to a subset whose sum is K.
- K cannot be chosen.
- For the numbers less than K, at most K/2 numbers can be chosen. For example:
- If K=5, 1+4=5, and 2+3=5, so either 1 can be chosen or 4 and similarly either 2 or 3 can be chosen. Thus, at most (5/2=2) numbers can be chosen.
- If K=6, 1+5=6, 2+4=6 and 3+3=6. Again, 3 numbers can be chosen such that no subset-sum equals 6. 3 can always be chosen as only distinct numbers are being chosen, and either 1 or 5 and similarly either 2 or 4 can be chosen. Thus, at most (6/3=3) numbers can be chosen.
- Therefore, the maximum number of distinct numbers that can be chosen is (N-K)+(K/2).
Follow the below steps to solve the problem:
- The maximum number of distinct digits that can be chosen is (N-K)+(K/2).
- All the numbers greater than K need to be chosen i.e N-K numbers from the end. K/2 elements less than K also need to be chosen.
- Thus, a possible solution is to choose (N-K)+(K/2) consecutive numbers starting from N and excluding K.
- The easiest way to do this is to create an array storing all values from 1 to N, except for K, reverse the array, and print (N-K)+(K/2) elements from the beginning.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum number of distinct integers// in [1, N] having no subset with sum equal to Kvoid findSet(int N, int K){ // Declare a vector to store // the required numbers vector<int> a; // Store all the numbers in [1, N] except K for (int i = 1; i <= N; i++) { if (i != K) a.push_back(i); } // Store the maximum number // of distinct numbers int MaxDistinct = (N - K) + (K / 2); // Reverse the array reverse(a.begin(), a.end()); // Print the required numbers for (int i = 0; i < MaxDistinct; i++) cout << a[i] << " ";} // Driver Codeint main(){ // Given Input int N = 5, K = 3; // Function Call findSet(N, K); return 0;} |
5 4 2
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


