Skip to content

Commit cb96b79

Browse files
committed
triplet sum close to target algorithms in python
1 parent cde5f5c commit cb96b79

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Diff for: python/triplet-sum-close-to-target.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Problem Statement
2+
# Given an array of unsorted numbers and a target number, find a triplet in the array whose sum is as close to the target number as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the triplet with the smallest sum.
3+
4+
# Example 1:
5+
6+
# Input: [-2, 0, 1, 2], target = 2
7+
# Output: 1
8+
# Explanation: The triplet[-2, 1, 2] has the closest sum to the target.
9+
# Example 2:
10+
11+
# Input: [-3, -1, 1, 2], target = 1
12+
# Output: 0
13+
# Explanation: The triplet[-3, 1, 2] has the closest sum to the target.
14+
# Example 3:
15+
16+
# Input: [1, 0, 1, 1], target = 100
17+
# Output: 3
18+
# Explanation: The triplet[1, 1, 1] has the closest sum to the target.
19+
20+
21+
22+
import math
23+
24+
25+
def triplet_sum_close_to_target(arr, target_sum):
26+
arr.sort()
27+
smallest_difference = math.inf
28+
for i in range(len(arr)-2):
29+
left = i + 1
30+
right = len(arr) - 1
31+
while (left < right):
32+
target_diff = target_sum - arr[i] - arr[left] - arr[right]
33+
if target_diff == 0: # we've found a triplet with an exact sum
34+
return target_sum # return sum of all the numbers
35+
36+
# the second part of the following 'if' is to handle the smallest sum when we have more than one solution
37+
if abs(target_diff) < abs(smallest_difference) or (abs(target_diff) == abs(smallest_difference) and target_diff > smallest_difference):
38+
smallest_difference = target_diff # save the closest and the biggest difference
39+
40+
if target_diff > 0:
41+
left += 1 # we need a triplet with a bigger sum
42+
else:
43+
right -= 1 # we need a triplet with a smaller sum
44+
45+
return target_sum - smallest_difference
46+
47+
48+
def main():
49+
print(triplet_sum_close_to_target([-2, 0, 1, 2], 2))
50+
print(triplet_sum_close_to_target([-3, -1, 1, 2], 1))
51+
print(triplet_sum_close_to_target([1, 0, 1, 1], 100))
52+
53+
54+
main()

0 commit comments

Comments
 (0)