You are given an integer array ranks where ranks[i] represents the rank of the ith student arriving in order. A lower number indicates a better rank.
Initially, the first student is selected by default.
A replacement occurs when a student with a strictly better rank arrives and replaces the current selection.
Return the total number of replacements made.
Example 1:
Input: ranks = [4,1,2]
Output: 1
Explanation:
ranks[0] = 4 is initially selected.ranks[1] = 1 is better than the current selection, so a replacement occurs.Example 2:
Input: ranks = [2,2,3]
Output: 0
Explanation:
ranks[0] = 2 is initially selected.ranks[1] = 2 or ranks[2] = 3 is better than the current selection.
Constraints:
1 <= ranks.length <= 1051 <= ranks[i] <= 105We use a variable cur to record the rank of the currently selected student. We iterate through the array ranks, and if we encounter a student with a better rank (i.e., ranks[i] < cur), we update cur and increment the answer by one.
After the iteration, we return the answer.
The time complexity is O(n), where n is the number of students. The space complexity is O(1).
Java
C++
Go
TypeScript
Practice Number of Student Replacements with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor