Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion:  and . The maximum length subarray has  elements.


Question from hackerrank..



Solution in C# - 


class Result
{

    public static int pickingNumbers(List<int> a)
    {
        a.Sort();
        int count = 1,x=a[0],ans=2;
        for(int i=1; i<a.Count; i++)
        {
            if((a[i]-x) <= 1)
                count++;
            else
            {
                ans = Math.Max(ans,count);
                x = a[i];
                count = 1;
            }
        }
        ans = Math.Max(ans,count);
        return ans;
    }

}

class Solution
{
    public static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> a = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(aTemp => Convert.ToInt32(aTemp)).ToList();

        int result = Result.pickingNumbers(a);

        textWriter.WriteLine(result);

        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post