Wednesday, November 19, 2014

Hacker Rank - Priyanka and Toys

Little Priyanka visited a kids' shop. There are N toys and their weight is represented by an array W=[w1,w2,,wN]. Each toy costs 1 unit, and if she buys a toy with weight w, then she can get all other toys whose weight lies between [w,w+4] (both inclusive) free of cost.
Input Format
The first line contains an integer N i.e. number of toys.
Next line will contain N integers, w1,w2,,wN, representing the weight array.
Output Format
Minimum units with which Priyanka could buy all of toys.
Solution C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
         Int32 N = Convert.ToInt32(Console.ReadLine());//5;
            Int32[] w = Console.ReadLine().ToString().Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); ; //{ 1, 2, 3, 17, 10 };

            Array.Sort(w);
            Int32 unit = 0; Int32 W = 0;
            for (int i = 0; i < w.Length; i++)
            {
                if (i == 0) { unit++; W = w[i]+4; }
                else
                {
                    if (w[i] > W) { unit++; W = w[i] + 4; }
                }

            }
            Console.WriteLine(unit);
    }
}

No comments:

Post a Comment