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.
Input: nums =[1,3,2,1,5,4], k =2Output: 12Explanation:
The good numbers are `nums[1] = 3`,`nums[4] = 5`, and `nums[5] = 4` because
they are strictly greater than the numbers at indices `i - k` and `i + k`.
The problem asks us to find elements that are strictly greater than their neighbors at a fixed distance k, if those neighbors exist. If either neighbor does not exist, the element is automatically considered good. By iterating through the array and checking these conditions for each element, we can efficiently identify and sum all good numbers.
For each index i, check if nums[i] is strictly greater than nums[i-k] and nums[i+k] (if those indices exist). If so, add nums[i] to the sum. If neither index exists, nums[i] is always good.
#include<vector>usingnamespace std;
classSolution {
public:int sumOfGoodNumbers(vector<int>& nums, int k) {
int n = nums.size(), sum =0;
for (int i =0; i < n; ++i) {
bool good = true;
if (i - k >=0&& nums[i] <= nums[i - k]) good = false;
if (i + k < n && nums[i] <= nums[i + k]) good = false;
if (good) sum += nums[i];
}
return sum;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintsumOfGoodNumbers(int[] nums, int k) {
int n = nums.length, sum = 0;
for (int i = 0; i < n; ++i) {
boolean good =true;
if (i - k >= 0 && nums[i]<= nums[i - k]) good =false;
if (i + k < n && nums[i]<= nums[i + k]) good =false;
if (good) sum += nums[i];
}
return sum;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funsumOfGoodNumbers(nums: IntArray, k: Int): Int {
val n = nums.size
var sum = 0for (i in0 until n) {
var good = trueif (i - k >=0&& nums[i] <= nums[i - k]) good = falseif (i + k < n && nums[i] <= nums[i + k]) good = falseif (good) sum += nums[i]
}
return sum
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsumOfGoodNumbers(self, nums: list[int], k: int) -> int:
n = len(nums)
total =0for i in range(n):
good =Trueif i - k >=0and nums[i] <= nums[i - k]:
good =Falseif i + k < n and nums[i] <= nums[i + k]:
good =Falseif good:
total += nums[i]
return total
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnsum_of_good_numbers(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
letmut sum =0;
for i in0..n {
letmut good =true;
if i asi32- k >=0&& nums[i] <= nums[(i asi32- k) asusize] { good =false; }
if i asi32+ k < n asi32&& nums[i] <= nums[(i asi32+ k) asusize] { good =false; }
if good { sum += nums[i]; }
}
sum
}
}
1
2
3
4
5
6
7
8
9
10
11
functionsumOfGoodNumbers(nums: number[], k: number):number {
constn=nums.length;
letsum=0;
for (leti=0; i<n; ++i) {
letgood=true;
if (i-k>=0&&nums[i] <=nums[i-k]) good=false;
if (i+k<n&&nums[i] <=nums[i+k]) good=false;
if (good) sum+=nums[i];
}
returnsum;
}