How to optimize solution to this problem

The problem is like this. There are n players. Two parameters, (coordination C and problem solving skills Ps) of each player are given. We have to select a team of two players, such that the absolute difference between coordination of both players, is less than a value (k, which is already given) and the sum of their problem solving skills is and absolute difference between coordination of both players is maximum.

i.e. abs(c1-c2) <=k


Maximize - ps1 + ps2 + abs(c1-c2).

I have tried this naively using two for loops with O(n^2) complexity. Is there any way we can optimize this?

link to the problem?

Let’s sort the array C, then your objective function is:
\max\limits_{i=1}^{n}\max\limits_{j =i}^{n} (ps[j] + c[j] + ps[i] - c[i]) which can be written as:
\max\limits_{i=1}^{n} (ps[i] - c[i] + (\max\limits_{j =i}^{n} ps[j] + c[j])). This can be easily done in O(N*log(N))

This problem was asked in NCR.

Kindly wait before the person provide you a direct link to the problem, it could be from some ongoing contest or hiring challenge.

I don’t know about this, can you share the link of contest?

Sure, I’ll remember this from next time.

It was from hiring challenge. You won’t be able to access it since it is private contest.