Skip to content

Instantly share code, notes, and snippets.

@alvinlau
Created August 9, 2022 06:26
Show Gist options
  • Select an option

  • Save alvinlau/3c047bc098d3fd3671e05bd1d74aecec to your computer and use it in GitHub Desktop.

Select an option

Save alvinlau/3c047bc098d3fd3671e05bd1d74aecec to your computer and use it in GitHub Desktop.
16. 3Sum Closest
# https://leetcode.com/problems/3sum-closest/
# 16. 3Sum Closest
# Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
# Return the sum of the three integers.
# You may assume that each input would have exactly one solution.
# Example 1:
# Input: nums = [-1,2,1,-4], target = 1
# Output: 2
# Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
# Example 2:
# Input: nums = [0,0,0], target = 1
# Output: 0
# Constraints:
# 3 <= nums.length <= 1000
# -1000 <= nums[i] <= 1000
# -104 <= target <= 104
# didn't pass the time limit in the submission
# have to do better than use combination
def three_sum_closest(nums, target)
# sorting doesn't do much since the target is not maximizing
sums = nums.combination(3).map(&:sum)
diffs = sums.uniq.map{|sum| [sum, (sum - target).abs]}
diffs.min{|a,b| a[1] <=> b[1]}[0]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment