You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.
Given the lengths of  sticks, print the number of sticks that are left before each iteration until there are none left.
For example, there are  sticks of lengths . The shortest stick length is , so we cut that length from the longer two and discard the pieces of length . Now our lengths are . Again, the shortest stick is of length , so we cut that amount from the longer stick and discard those pieces. There is only one stick left, , so we discard that stick. Our lengths are .
 Description
It should return an array of integers representing the number of sticks before each cut operation is performed.
cutTheSticks has the following parameter(s):
  • arr: an array of integers representing the length of each stick
Input
The first line contains a single integer , the size of .
The next line contains  space-separated integers, each an  where each value represents the length of the  stick.
Output
For each operation, print the number of sticks that are present before the operation on separate lines.
Question from hackerrank.

Solution in C# -


class Solution {
    static int[] cutTheSticks(int[] arr) {            
        int n = arr.Length;
        List<int> lens = new List<int>();
        while(n!=0)
        {
            lens.Add(n);
            int min = int.MaxValue;      
            for(int j=0; j<arr.Length; j++)
                if(arr[j] < min && arr[j] > 0)
                    min = arr[j];
            for(int i=0; i<arr.Length; i++)
            {
                arr[i] -= min;
                if(arr[i] == 0)
                    n--;
            }
        }
        return lens.ToArray();
    }
    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        int n = Convert.ToInt32(Console.ReadLine());
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp)) ;
        int[] result = cutTheSticks(arr);
        textWriter.WriteLine(string.Join("\n", result));
        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post