- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if nums[i] + nums[j] > target, then
- return answer
Let us see the following implementation to get better understanding −
Example
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
Advertisements