Answer to Question #338101 in Java | JSP | JSF for mahi

Question #338101

A special unit is formed within the police force of N policeman,such that no 2 policeman have equal ranking. The rank of a policeman is depicted by the number of 

stars in his badge. There are a total of N policeman each having a badge containing some stars.

your task is to calculate the minimum number of extra starsthat need to be bought in order to meet the above constraint.

Note: A star cannot be removed from a badge.

Input Specification:

input1: N denoting the number of policeman in the special unit.

input2: An array of N elements[A1,A2,..AN] where Ai denotes the number of stars on the badge Ai.

Output Specification:

Your function should return the minimum number of extra stars required.



1
Expert's answer
2022-05-06T15:35:09-0400
import java.util.Arrays;
import java.util.Scanner;

public class Answer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter N denoting the number of policeman in the special unit: ");
        int n = scanner.nextInt();
        System.out.println("Enter an array of N elements: ");
        int[] pol = new int[n];
        for (int i = 0; i < n; i++) {
            pol[i] = scanner.nextInt();
        }
        int ans = 0;
        Arrays.sort(pol);
        for (int i = 0; i < n - 1; i++) {
            if (pol[i] >= pol[i + 1]) {
                while (pol[i] >= pol[i + 1]) {
                    pol[i + 1]++;
                    ans++;
                }
            }
        }
        System.out.println("Extra stars: " + ans);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS