[LeetCode] Happy Students

2860. Happy Students

You are given a 0-indexed integer array nums of length n where n is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.

The ith student will become happy if one of these two conditions is met:

  • The student is selected and the total number of selected students is strictly greater than nums[i].
  • The student is not selected and the total number of selected students is strictly less than nums[i].

Return the number of ways to select a group of students so that everyone remains happy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int countWays(vector<int>& nums) {
int res = 0;
sort(begin(nums), end(nums));
for(int i = 0; i < nums.size(); i++) {
int now = nums[i], nxt = i + 1 == nums.size() ? INT_MAX : nums[i+1];
if((i + 1) > now and (i + 1) < nxt) res += 1;
}
if(nums[0] != 0) res += 1;
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/17/PS/LeetCode/happy-students/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.