
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if nums[p1] + nums[p2] < target, then
- 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
- Related Articles
- Program to find lowest sum of pairs greater than given target in Python
- Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10
- Two Sum Less Than K in Python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to find list of elements which are less than limit and XOR is maximum in Python
- Find the sum of all natural numbers that are less than 100 and divisible by 4.
- Program to find two non-overlapping sub-arrays each with target sum using Python
- The sum of the squares of two numbers is 233 and one of the numbers is 3 less than twice the other number. Find the numbers.
- Product of subarray just less than target in JavaScript
- Program to find number of sublists whose sum is given target in python
- Program to find number of distinct quadruple that forms target sum in python
- 8085 program to count number of elements which are less than 0A
- Program to find two pairs of numbers where difference between sum of these pairs are minimized in python
- The sum of two consecutive numbers are 45 find the numbers.

Advertisements