Program to find lowest sum of pairs greater than given target in Python


Suppose we have a list of numbers called nums and another value target. We have to find the lowest sum of pair of numbers that is larger than target.

So, if the input is like nums = [2, 4, 6, 10, 14] target = 10, then the output will be 12, as we pick 2 and 10

To solve this, we will follow these steps −

  • sort the list nums
  • n := size of nums
  • answer := 10^10
  • i := 0, j := n - 1
  • while i < j, do
    • if nums[i] + nums[j] > target, then
      • answer := minimum of answer and (nums[i] + nums[j])
      • j := j - 1
    • otherwise,
      • i := i + 1
  • return answer

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, target): nums.sort()
      n = len(nums)
      answer = 10 ** 10
      i, j = 0, n - 1
      while i < j:
         if nums[i] + nums[j] > target:
            answer = min(answer, nums[i] + nums[j])
            j -= 1
         else:
            i += 1
      return answer
ob = Solution()
nums = [2, 4, 6, 10, 14]
target = 10
print(ob.solve(nums, target))

Input

[2, 4, 6, 10, 14], 10

Output

12

Updated on: 20-Nov-2020

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements