Closest Numbers

  • + 1 comment

    Here it is in C# with linq. The preamble to the problem made the answer simple. Sort the list. You're guaranteed that any two elements that have the closest values will be next to each other (otherwise, they wouldn't be the closest to each other). Keep track of the shortest distance, whenever you find a new shortest distance you can clear out the result string.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    class Solution {
        static void Main(String[] args) {
          var count = int.Parse(Console.ReadLine());
          var values = Console.ReadLine().Split(' ').Select(str=>int.Parse(str)).OrderBy(v=>v).ToArray();
          int diff = int.MaxValue;
          int? previousValue = null;
          string retVal = "";
          foreach(var number in values){
              if(previousValue==null){
                  previousValue = number;
              }
              else{
                  var newDiff = Math.Abs(number-previousValue.Value);
                  if (newDiff < diff){
                      retVal="";
                      diff=newDiff;
                  }
                  if (newDiff==diff){
                      retVal= retVal + previousValue + " " + number + " ";
                  }
                  previousValue=number;
              }
          }
          Console.WriteLine(retVal.Trim());
      }
    

    }