Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 21:45
Show Gist options
  • Save evidanary/aaf2ae68c4bedc6c510a5e74476de2f8 to your computer and use it in GitHub Desktop.
Save evidanary/aaf2ae68c4bedc6c510a5e74476de2f8 to your computer and use it in GitHub Desktop.
# check if there is three integers which sum up to the targeted sum
# fix k from 0...size-2 and then run sum of 2 numbers equal to target (see above)
def target_sum(arr, target)
arr.sort!
size = arr.size
i, j = 0, size-1
count = 0
(0...size-2).each do |k|
i=k+1
j=size-1
while(i<j) do
sum = arr[i] + arr[j] + arr[k]
if sum == target
count += 1
i+=1
elsif sum < target
i += 1
else
j -= 1
end
end
end
count
end
puts target_sum([0,1,2,3,4,5], 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment