See the original problem on HackerRank.
Solutions
We can find the answer by sorting one of the arrays in ascending order and the other in descending order. Then we check if the sum of all elements in pairs is greater than or equal to \(K\).
It’s a greedy algorithm and its proof is left to the reader (see here).
In C++:
|
|
This code hides some patterns - in C# by Simone Busoli and Antonio D’Angelico:
|
|
Conceptually, in C++ one can use inner_product
(left to the reader), although
it goes to the end even if a failing condition is found.
C++20 will have ranges and it will be possibile to write such a solution:
|
|
Everything is lazy, meaning that zip
and all_of
keeps on generating
results until all_of
’s condition is false.
An Haskell solution by alepez:
|
|
A similar solution in Python by enrico_lovisotto
|
|