Program to find sum of two numbers which are less than the target in Python


Suppose we have a list of numbers called nums and also have a target value, we have to find the sum of the largest pair of numbers in nums whose sum is at most (target-1).

So, if the input is like nums = [8, 3, 4, 9, 2] target = 8, then the output will be 7, because the sum of the largest pair of numbers less than 8 is 4 + 3 = 7.

To solve this, we will follow these steps −

  • sort the list nums
  • p1 := 0
  • p2 := size of nums - 1
  • m := -inf
  • while p1 < p2, do
    • if nums[p1] + nums[p2] < target, then
      • m := maximum of m and (nums[p1] + nums[p2])
      • p1 := p1 + 1
    • otherwise,
      • p2 := p2 - 1
  • return m

Example

Let us see the following implementation to get better understanding −

import math
def solve(nums, target):
   nums.sort()
   p1 = 0
   p2 = len(nums) - 1
   m = -math.inf
   while p1 < p2:
      if nums[p1] + nums[p2] < target:
         m = max(m, nums[p1] + nums[p2])
         p1 += 1
      else:
         p2 -= 1
   return m

nums = [8, 3, 4, 9, 2]
target = 8
print(solve(nums, target))

Input

[8, 3, 4, 9, 2], 8

Output

7

Updated on: 14-Oct-2021

497 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements