Thursday, November 8, 2018

Q6: Find the pair in sorted list whose sum is closest or same as value of x

Question 6: Given a sorted array and a number x, find the pair in array whose sum is closest to or same as x
 Examples:
 Input: [2, 10, 22, 28, 29, 30, 40,51], x = 54
 Output: 2 and 51
 Input: [1, 3, 5, 7, 10], x = 15
 Output: 5 and 10

3 comments:

  1. from itertools import combinations
    #sorted_array = [1, 3, 5, 7, 10]
    #x = 15
    sorted_array = [2, 22, 28, 29, 30, 51]
    x = 54
    pair_array = list(filter(lambda v: sum(v) <= x, list(combinations(sorted_array, 2))))
    sorted_pair = sorted(pair_array, key=lambda x: sum(x))[-1]
    print('%s and %s'%(sorted_pair[0], sorted_pair[1]))

    ReplyDelete
  2. Nice logic!! good use of existing modules!!!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete