1894. Find the Student that Will Replace the Chalk
Difficulty: Medium
Topics: Array, Binary Search, Simulation, Prefix Sum
There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.
You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.
Return the index of the student that will replace the chalk pieces.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
Let's break down the problem step by step:
Total Chalk Consumption:
First, calculate the total amount of chalk needed for one complete round (from student 0 to student n-1). This will help us reduce the value of k by taking into account how many complete rounds can be covered by k pieces of chalk.
Reduce k by Modulo:
If k is larger than the total chalk required for one complete round, we can simplify the problem by taking k % total_chalk. This operation will give us the remaining chalk after as many full rounds as possible, leaving us with a smaller problem to solve.
Find the Student Who Runs Out of Chalk:
Iterate through each student's chalk consumption, subtracting it from k until k becomes less than the current student's chalk requirement. The index of this student is our answer.
Let's take an example chalk = [3, 4, 1, 2] and k = 25:
text{total_chalk} = 3 + 4 + 1 + 2 = 10
k % 10 = 25 % 10 = 5
Now we have k = 5 after subtracting as many full rounds as possible.
Let's implement this solution in PHP: 1894. Find the Student that Will Replace the Chalk
Explanation:
- Total Chalk Sum: We sum up all the chalk requirements to get the total for one complete round.
- Modulo Operation: Using modulo with k, we get the effective number of chalks to distribute after full rounds.
- Find the Student: We then iterate through the students, checking if the remaining chalk is sufficient. The first time it's insufficient, that student's index is the answer.
Complexity:
This approach ensures that the problem is solved efficiently even for large inputs.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Find the Student that Will Replace the Chalk. For more information, please follow other related articles on the PHP Chinese website!