- Related Questions & Answers
- Maximum difference between two subsets of m elements in C
- Elements of an array that are not divisible by any element of another array in C++
- Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++
- Count the number of elements in an array which are divisible by k in C++
- Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++
- Product of all the elements in an array divisible by a given number K in C++
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k in C++
- Find elements of an array which are divisible by N using STL in C++
- XOR of all elements of array with set bits equal to K in C++
- Find K Closest Elements in C++
- Find k maximum elements of array in original order in C++
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
- Find elements of array using XOR of consecutive elements in C++
- Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N in C++
- Find the number closest to n and divisible by m in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array with N positive integers, and another variable K. We have to find the exactly m-elements, such that difference between any two elements is equal to k. So if the array is A = [4, 7, 10, 6, 9], and k = 3 and m = 3, then output will be “yes”. As we can find three elements like 4, 7, 10.

To solve this, we have to keep track of the remainders, when an element is divided by k. Now create a multi-dimensional array rem[][] of size k, its index is showing the remainder, and elements will be the elements as per their corresponding remainders when divided by k. Now by traversing the remainder set, we can get a set whose size is greater than or equal to the required size m if exists. And the difference of any elements of that set will be divisible by k.

#include<iostream> #include<vector> using namespace std; void searchElementsSet(int arr[], int n, int k, int m) { vector<int> rem_matrix[k]; for (int i = 0; i < n; i++) { int rem = arr[i] % k; rem_matrix[rem].push_back(arr[i]); } for (int i = 0; i < k; i++) { if (rem_matrix[i].size() >= m) { cout << "Yes Possible"<<endl; for (int j = 0; j < m; j++) cout << rem_matrix[i][j] << " "; return; } } cout << "Impossible"; } int main() { int arr[] = {4, 7, 10, 6, 9}; int k = 3; int m = 3; int n = sizeof(arr) / sizeof(arr[0]); searchElementsSet(arr, n, k, m); }

Yes Possible 4 7 10

Advertisements