Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created May 30, 2014 04:18
Show Gist options
  • Save gabhi/e081516379caf4dc5f97 to your computer and use it in GitHub Desktop.
Save gabhi/e081516379caf4dc5f97 to your computer and use it in GitHub Desktop.
Finding three elements in an array whose sum is closest to an given number
for (i in 1..n-2) {
j = i+1 // Start right after i.
k = n // Start at the end of the array.
while (k >= j) {
// We got a match! All done.
if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])
// We didn't match. Let's try to get a little closer:
// If the sum was too big, decrement k.
// If the sum was too small, increment j.
(A[i] + A[j] + A[k] > 0) ? k-- : j++
}
// When the while-loop finishes, j and k have passed each other and there's
// no more useful combinations that we can try with this i.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment