instagram

Cut the sticks – hackerrank

Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations.

Example One
Input :
4
3 2 8 7

Output :
4
3
2
1

Example Two

Input :
5
3 3 2 2 1

Output:
5
4
2

Code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class CutTheSticks2 {
	public static void main(String s[]) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		short N = Short.parseShort(br.readLine());
		short[] A = new short[N];
		N = 0;
		for (String str : br.readLine().split(" ")) {
			A[N++] = Short.parseShort(str);
		}

		Arrays.sort(A);

		StringBuffer sb = new StringBuffer();
		System.out.println(N);
		for (int i = 1; i < N; i++) {
			if (A[i - 1] != A[i]) {
				sb.append((N - i) + "\n");
			}
		}

		// OUTPUT
		System.out.print(sb);
	}
}

Share