- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

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

7

- Related Questions & Answers
- Two Sum Less Than K 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
- Program to find lowest sum of pairs greater than given target in Python
- Program to find list of elements which are less than limit and XOR is maximum in Python
- 8085 program to count number of elements which are less than 0A
- 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
- Product of subarray just less than target in JavaScript
- Sum of two elements just less than n in JavaScript\n
- Find the Number of subarrays having sum less than K using C++
- C program to find sum and difference of two numbers
- Program to find two pairs of numbers where difference between sum of these pairs are minimized in python
- Program to find two non-overlapping sub-arrays each with target sum using Python
- Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
- Find Smallest Letter Greater Than Target in Python

Advertisements