Hiring Test codechef solution in c++
Here is a solution to the Hiring Test problem on CodeChef, implemented in C++:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> b(m);
for (int i = 0; i < m; i++) {
cin >> b[i];
}
sort(a.begin(), a.end());
int maxDiff = 0;
int maxDiffIndex = -1;
for (int i = 0; i < n; i++) {
int diff = b[0] - a[i];
if (diff > maxDiff) {
maxDiff = diff;
maxDiffIndex = i;
}
}
cout << a[maxDiffIndex] << " " << b[0] << endl;
return 0;
}
Explanation:
We start by including necessary libraries for our program:
iostream
,vector
, andalgorithm
. These libraries provide us with input/output operations, dynamic arrays (vectors), and thesort
function, respectively.We declare two variables,
n
andm
, to store the number of elements in the arraysa
andb
, respectively. We read these values from the standard input using thecin
object.We declare a vector
a
of sizen
to store the elements of arraya
, and then we read the elements ofa
from the standard input using a loop.Similarly, we declare a vector
b
of sizem
to store the elements of arrayb
, and then we read the elements ofb
from the standard input using a loop.We sort the vector
a
in ascending order using thesort
function from thealgorithm
library. This will help us find the element ina
that is closest to the smallest element inb
.We declare two variables,
maxDiff
andmaxDiffIndex
, to keep track of the maximum difference and the index of the corresponding element ina
. We initializemaxDiff
to 0 andmaxDiffIndex
to -1.We iterate through each element in
a
using a loop. For each element, we calculate the difference between the smallest element inb
and the current element ina
. If this difference is greater than the current maximum difference (maxDiff
), we updatemaxDiff
andmaxDiffIndex
accordingly.Finally, we print the element in
a
at indexmaxDiffIndex
and the smallest element inb
as the output.We return 0 to indicate successful execution of the program.
Note: This solution finds the element in a
that is closest to the smallest element in b
, based on the difference between the two.