Intro: As far as I could search, this question wasn\'t asked in SO yet.
This is an interview question.
I am not even specifically looking for a code sol
How about that: you find k
smallest numbers (or more precisely their indices) (k
big enough, let say 10
). It is sure, that the wanted pair is between them. Now you just check the possible 50
pairs and select the best which satisfies the constraints.
You don't need 10
, less would do - but more than 3
:)
Edit: finding k
smallest numbers is O(n)
, because you just keep the best 10
for example in a heap (add new element, delete maximum O(k*logk)=O(1)
operations).
Then there will be a pair which satisfy the constraints (not next to each other). It is also clear that, if you build the sum with an element not from those k
, it would be bigger than the best pair chosen from those k
elements.
Checking at most k*k
pairs is also O(1)
, thus the whole running time is O(n)
.