Skip to content

2860. Happy Students 👎

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countWays(vector<int>& nums) {
    nums.push_back(-1);
    nums.push_back(INT_MAX);
    ranges::sort(nums);

    int ans = 0;

    // i := the number of the selected numbers
    for (int i = 0; i + 1 < nums.size(); ++i)
      if (nums[i] < i && i < nums[i + 1])
        ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int countWays(List<Integer> nums) {
    nums.add(-1);
    nums.add(Integer.MAX_VALUE);
    Collections.sort(nums);

    int ans = 0;

    // i := the number of the selected numbers
    for (int i = 0; i + 1 < nums.size(); ++i)
      if (nums.get(i) < i && i < nums.get(i + 1))
        ++ans;

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def countWays(self, nums: list[int]) -> int:
    return sum(a < i < b
               for i, (a, b) in  # i := the number of the selected numbers
               enumerate(itertools.pairwise([-1] + sorted(nums) + [math.inf])))