[LeetCode] Find the Student that Will Replace the Chalk

1894. Find the Student that Will Replace the Chalk

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int chalkReplacer(vector<int>& chalk, int k) {
int n = chalk.size();
vector<long long> psum(n, chalk[0]);
for(int i = 1; i < n; i++) {
psum[i] = psum[i-1] + chalk[i];
}
k %= psum.back();
return upper_bound(begin(psum), end(psum), k) - begin(psum);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/25/PS/LeetCode/find-the-student-that-will-replace-the-chalk/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.