- Related Questions & Answers
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to find sum of unique elements in Python
- Find three closest elements from given three sorted arrays in C++
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Program to find sum of rectangle whose sum at most k 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
- Find K Closest Elements in C++
- Python program to find sum of elements in list
- 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
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find the product of three elements when all are unique in Python
- Program to find a list of numbers where each K-sized window has unique elements in Python
- Find k closest elements to a given value in C++

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

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

[2, 5, 25, 6], 14

1

Advertisements