- 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

# Program to find three unique elements from list whose sum is closest to k Python

Suppose we have a list of numbers called nums and another value k, we have to find three unique entries in nums (a, b, c) such that |a + b + c − k| is minimized and return the absolute difference.

So, if the input is like nums = [2, 5, 25, 6] k = 14, then the output will be 1 as if we take [2, 5, 6] will get us closest to 14 and the absolute difference is |13 − 14| = 1.

To solve this, we will follow these steps −

sort the list nums

ans := 1^9

for i in range 0 to size of nums, do

j := i + 1

k := size of nums − 1

while j < k, do

s := nums[i] + nums[j] + nums[k]

if s <= target, then

ans := minimum of ans and target − s

j := j + 1

otherwise,

ans := minimum of ans and s − target

k := k − 1

return ans

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums, target): nums.sort() ans = 1e9 for i in range(len(nums)): j = i + 1 k = len(nums) − 1 while j < k: s = nums[i] + nums[j] + nums[k] if s <= target: ans = min(ans, target - s) j += 1 else: ans = min(ans, s - target) k −= 1 return ans ob1 = Solution() nums = [2, 5, 25, 6] k = 14 print(ob1.solve(nums, k))

## Input

[2, 5, 25, 6], 14

## Output

1

- Related Questions & Answers
- Program to check we can find three unique elements ose sum is same as k or not Python
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Program to find sum of unique elements in Python
- Find three closest elements from given three sorted arrays in C++
- Program to find sum of rectangle whose sum at most k in Python
- C++ code to find three numbers whose sum is n
- Program to find sum of odd elements from list in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to check we can find four elements whose sum is same as k or not in Python
- Program to find closest subsequence sum in Python
- Find K Closest Elements in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to count number of paths whose sum is k in python
- Program to find a sub-list of size at least 2 whose sum is multiple of k in Python
- Python program to find sum of elements in list