2 minute read

Climbing the Leaderboard (Hacker Rank)

Alice is playing an arcade game and wants to climb to the top of the leaderboard. Can you help her track her ranking as she beats each level? The game uses Dense Ranking, so its leaderboard works like this:

The player with the highest score is ranked number on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number. For example, four players have the scores , , , and . Those players will have ranks , , , and , respectively.

When Alice starts playing, there are already people on the leaderboard. The score of each player is denoted by . Alice plays for levels, and we denote her total score after passing each level as . After completing each level, Alice wants to know her current rank.

You are given an array, , of monotonically decreasing leaderboard scores, and another array, , of Alice’s cumulative scores for each level of the game. You must print integers. The integer should indicate the current rank of alice after passing the level.

Input Format

The first line contains an integer, , denoting the number of players already on the leaderboard. The next line contains space-separated integers describing the respective values of . The next line contains an integer, , denoting the number of levels Alice beats. The last line contains space-separated integers describing the respective values of .

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] scores = new int[n];
        for(int scores_i = 0; scores_i < n; scores_i++){
            scores[scores_i] = in.nextInt();
        }
        int m = in.nextInt();
        int[] alice = new int[m];
        for(int alice_i = 0; alice_i < m; alice_i++){
            alice[alice_i] = in.nextInt();
        }
        int maxRank = 1;
        for (int i = 1; i < n; i++) {
            if (scores[i] != scores[i - 1]) {
                maxRank++;
            }
        }

        int rank = maxRank + 1;
        int cursor = n - 1;
        for (int a = 0; a < m; a++) {
            while (cursor >= 0 && alice[a] >= scores[cursor]) {
                boolean flag = false;
                do {
                    cursor--;
                    if (!flag) {
                        rank = Math.max(1, rank - 1);
                        flag = true;
                    }
                } while (cursor > 0 && scores[cursor + 1] == scores[cursor]);
            }

            System.out.println(rank);

        }
        in.close();
    }
}

행운의 77문제 프로젝트
  행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.
  (한달은 이미 많이 지났지만...그래도 77문제는 될 수 있도록!)