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.
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());
}
}
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 →
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.
}