Created
May 30, 2014 04:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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