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.

Algorithm

To solve this, we will follow these steps ?

  • Sort the list nums
  • Initialize p1 := 0 (left pointer)
  • Initialize p2 := size of nums - 1 (right pointer)
  • Initialize m := -inf (maximum sum found)
  • While p1
  • If nums[p1] + nums[p2]
  • 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))
    

    The output of the above code is ?

    7
    

    How It Works

    The algorithm uses the two-pointer technique on a sorted array:

    • After sorting: [2, 3, 4, 8, 9]
    • Left pointer starts at 0, right pointer at last index
    • If sum
    • If sum >= target, move right pointer left to reduce the sum

    Alternative Approach

    Here's another implementation without using math.inf ?

    def find_max_sum(nums, target):
        nums.sort()
        left, right = 0, len(nums) - 1
        max_sum = -1
        
        while left < right:
            current_sum = nums[left] + nums[right]
            
            if current_sum < target:
                max_sum = max(max_sum, current_sum)
                left += 1
            else:
                right -= 1
        
        return max_sum
    
    numbers = [8, 3, 4, 9, 2]
    target_value = 8
    result = find_max_sum(numbers, target_value)
    print(f"Maximum sum less than {target_value}: {result}")
    

    The output of the above code is ?

    Maximum sum less than 8: 7
    

    Conclusion

    The two-pointer technique efficiently finds the maximum sum of pairs less than target in O(n log n) time complexity due to sorting. This approach is optimal for this problem as it avoids checking all possible pairs.

    Updated on: 2026-03-26T16:39:23+05:30

    792 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements