We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
one simple algorithm:
0. get the inputs from console
1. sort the input array as sortedInput
2. set lowestDiff to maximum integer value
3. set resultArray to empty array
4. for i = 1 to length of sortedInput-1
4a. delta = absolute value (sortedInput[i] - sortedInput[i-1])
4b. if delta < lowestDiff, then
-> lowestDiff = delta
-> clear resultArray (remove all elements from array)
-> add to resultArray sortedInpit[i-1], and then sortedInput[i]
4c. Else, if delta == lowestDiff, then
-> add to resultArray sortedInpit[i-1], and then sortedInput[i]
5. print resultArray as space-separated integer on single line.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
one simple algorithm:
0. get the inputs from console
1. sort the input array as sortedInput
2. set lowestDiff to maximum integer value
3. set resultArray to empty array
4. for i = 1 to length of sortedInput-1
4a. delta = absolute value (sortedInput[i] - sortedInput[i-1])
4b. if delta < lowestDiff, then
-> lowestDiff = delta
-> clear resultArray (remove all elements from array)
-> add to resultArray sortedInpit[i-1], and then sortedInput[i]
4c. Else, if delta == lowestDiff, then
-> add to resultArray sortedInpit[i-1], and then sortedInput[i]
5. print resultArray as space-separated integer on single line.