Similar Problems

Similar Problems not available

Reward Top K Students - Leetcode Solution

Companies:

LeetCode:  Reward Top K Students Leetcode Solution

Difficulty: Medium

Topics: hash-table string heap-priority-queue array sorting  

The "Reward Top K Students" problem on LeetCode is a simple problem that requires finding the top K students from a given list of student scores and assigning them rewards in descending order.

The problem statement is as follows:

You are given an integer array named "scores" representing the scores of the students in a class. The students are to be rewarded in the following way:

  1. The student with the highest score will receive an award.
  2. The student with the second-highest score will receive an award, but with a smaller value than the first prize.
  3. The student with the third-highest score will receive an award, but with an even smaller value than the second prize, and so on until the last student.
  4. The last student (Kth student) will receive the smallest prize or no prize if the class has fewer than K students.

Your task is to implement a function named "findReward" that will take the "scores" array and the value of K as input and return an array representing the rewards assigned to each student.

Example:

Input: scores = [10,20,30,40,50], K = 3 Output: [3, 2, 1, 0, 0]

Explanation: The first three students (50, 40, 30) get rewards. Award 1 goes to the student with the highest score (50), and has a value of 3. Award 2 goes to the student with the second-highest score (40), and has a value of 2. Award 3 goes to the student with the third-highest score (30), and has a value of 1. The remaining students (20, 10) get no rewards.

Solution:

One possible solution to this problem is to sort the scores array in descending order and assign rewards to each student based on their sorted order. We can start by assigning the first prize to the student with the highest score, then the second prize to the student with the second-highest score, and so on until the Kth student.

If there are fewer than K students in the list, we can assign a reward of zero to the remaining students. The implementation of the function "findReward" would look like this:

def findReward(scores, K): # Sort the scores in descending order sorted_scores = sorted(scores, reverse=True) # Initialize an array to store the rewards rewards = [0] * len(scores) # Assign rewards to K students with the highest scores for i in range(K): j = scores.index(sorted_scores[i]) rewards[j] = K - i return rewards

This solution has a time complexity of O(nlogn) due to the sorting algorithm used to sort the scores array. If the array is already sorted or partially sorted, we can avoid this sorting step and achieve a linear time complexity of O(n) by using a heap or a selection algorithm to find the K highest scores.

Reward Top K Students Solution Code

1