Skip to content

3452. Sum of Good Numbers

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

    for (int i = 0; i < n; ++i)
      if ((i - k < 0 || nums[i] > nums[i - k]) &&
          (i + k >= n || nums[i] > nums[i + k]))
        sum += nums[i];

    return sum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int sumOfGoodNumbers(int[] nums, int k) {
    final int n = nums.length;
    int sum = 0;

    for (int i = 0; i < n; ++i)
      if ((i - k < 0 || nums[i] > nums[i - k]) && //
          (i + k >= n || nums[i] > nums[i + k]))
        sum += nums[i];

    return sum;
  }
}
1
2
3
4
5
class Solution:
  def sumOfGoodNumbers(self, nums: list[int], k: int) -> int:
    return sum(num for i, num in enumerate(nums)
               if (i - k < 0 or num > nums[i - k])
               and (i + k >= len(nums) or num > nums[i + k]))