Skip to content

2455. Average Value of Even Numbers That Are Divisible by Three 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int averageValue(vector<int>& nums) {
    int sum = 0;
    int count = 0;

    for (const int num : nums)
      if (num % 6 == 0) {
        sum += num;
        ++count;
      }

    return count == 0 ? 0 : sum / count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int averageValue(int[] nums) {
    int sum = 0;
    int count = 0;

    for (final int num : nums)
      if (num % 6 == 0) {
        sum += num;
        ++count;
      }

    return count == 0 ? 0 : sum / count;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def averageValue(self, nums: list[int]) -> int:
    summ = 0
    count = 0

    for num in nums:
      if num % 6 == 0:
        summ += num
        count += 1

    return 0 if count == 0 else summ // count