[LeetCode] Sum of Good Numbers

3452. Sum of Good Numbers

Given an array of integers nums and an integer k, an element nums[i] is considered good if it is strictly greater than the elements at indices i - k and i + k (if those indices exist). If neither of these indices exists, nums[i] is still considered good.

Return the sum of all the good elements in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

func sumOfGoodNumbers(nums []int, k int) int {
res := 0
n := len(nums)
for i := 0; i < n; i++ {
ok := true
if i - k >= 0 && nums[i] <= nums[i-k] {
ok = false
}
if i + k < n && nums[i] <= nums[i+k] {
ok = false
}
if ok {
res += nums[i]
}
}
return res
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/16/PS/LeetCode/sum-of-good-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.