Given an array, what is the most time- and space-efficient algorithm to find the sum of two elements farthest from zero in that array?
Edit
For example, [1, -1, 3, 6, -10] has the farthest sum equal to -11 which is equal to (-1)+(-10).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a tournament comparison method to find the largest and second largest elements uses the fewest comparisons, in total
n+log(n)-2. Do this twice, once to find the largest and second largest elements, sayZandY, and again to find the smallest and second smallest elements, sayAandB. Then the answer is eitherZ+Yor-A-B, so one more comparison solves the problem. Overall, this takes2n+2log(n)-3comparisons. This is stillO(n), but in practice is faster than scanning the entire list4times to findA,B,Y,Z(in total uses4n-5comparisons).The tournament method is nicely explained with pictures and sample code in these two tutorials: one and two