• + 23 comments

    Java solution - passes 100% of test cases

    From my HackerRank solutions.

    Hint: Sort the array

    import java.util.Scanner;
    import java.util.Arrays;
    
    public class Solution {
        public static void main(String[] args) {
            /* Save Input */
            Scanner scan = new Scanner(System.in);
            int numSticks = scan.nextInt();
            int [] array = new int[numSticks];
            for (int i = 0; i < numSticks; i++) {
                array[i] = scan.nextInt();
            }
            scan.close();
            
            Arrays.sort(array);
            
            System.out.println(array.length);
            for (int i = 1; i < array.length; i++) {
                if (array[i] != array[i-1]) {
                    System.out.println(array.length - i);
                }
            }
        }
    }
    

    For input

    6
    5 4 4 2 2 8
    

    we sort the array and get

    2 2 4 4 5 8
    

    Our output is

    6 // we always print the full size of array before the for loop
    4 // since array[2] != array[1]
    2 // since array[4] != array[3]
    1 // since array[5] != array[4]
    

    As we traverse the array from left to right, every time we reach a new number, we can consider that as "cutting the sticks" for the numbers we already traverse.