Sum of Good Numbers - Problem
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 & Output
Example 1 — Basic Case
$
Input:
nums = [3,4,2,1,6,5], k = 2
›
Output:
18
💡 Note:
nums[0]=3 is good (no left neighbor, 3 > nums[2]=2). nums[1]=4 is good (no left neighbor, 4 > nums[3]=1). nums[4]=6 is good (6 > nums[2]=2, no right neighbor). nums[5]=5 is good (5 > nums[3]=1, no right neighbor). Sum = 3 + 4 + 6 + 5 = 18
Example 2 — Small Array
$
Input:
nums = [1,2,3], k = 1
›
Output:
3
💡 Note:
nums[0]=1 is not good (no left neighbor, but 1 ≤ nums[1]=2). nums[1]=2 is not good (2 > nums[0]=1 but 2 ≤ nums[2]=3). nums[2]=3 is good (3 > nums[1]=2, no right neighbor). Sum = 3
Example 3 — Edge Case
$
Input:
nums = [5], k = 1
›
Output:
5
💡 Note:
Single element with no neighbors at i-1 or i+1, so it's automatically good. Sum = 5
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code