Closest Numbers

  • + 0 comments

    Here is Simple Ruby Solution

    def closestNumbers(arr)
        # Write your code here
        arr.sort!  # Sort the array
        min_diff = Float::INFINITY
        result = []
    
        # Iterate through the array to find the minimum difference
        (0...arr.length - 1).each do |i|
            diff = (arr[i + 1] - arr[i]).abs
    
            if diff < min_diff
            min_diff = diff
            result = [[arr[i], arr[i + 1]]]  # Reset the result with the new closest pair
            elsif diff == min_diff
            result << [arr[i], arr[i + 1]]  # Add the pair if it has the same min difference
            end
        end
    
        result
    end