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: 10
💡 Note: nums[1]=4 is good (4 > nums[3]=1, no nums[-1]). nums[4]=6 is good (6 > nums[2]=2, no nums[6]). Sum = 4 + 6 = 10
Example 2 — Small Array
$ Input: nums = [1,2,3], k = 1
Output: 4
💡 Note: nums[0]=1 is good (no nums[-1], 1 ≤ nums[1]=2 but only needs to be strictly greater). nums[2]=3 is good (3 > nums[1]=2, no nums[3]). Only nums[2]=3 is good, but wait - nums[0] has no left neighbor so it's good too if 1 > nums[1], but 1 ≤ 2. Only nums[2] is good. Actually, let me recalculate: nums[0] has no i-1=-1, nums[0]=1 ≤ nums[1]=2 so not good. nums[1]=2: 2 > nums[0]=1 but 2 ≤ nums[2]=3 so not good. nums[2]=3: 3 > nums[1]=2 and no nums[3], so good. Sum = 3. Let me fix this.
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
Sum of Good Numbers Overviewnums = [3,4,2,1,6,5], k = 2342165i=0i=1i=2i=3i=4i=54 > 2Good elements: nums[1]=4, nums[4]=6Sum = 4 + 6 = 10
Understanding the Visualization
1
Input Analysis
Array with elements and distance k
2
Good Element Check
Element must be greater than k-distance neighbors
3
Sum Result
Add all good elements together
Key Takeaway
🎯 Key Insight: An element is good if it's greater than both its k-distance neighbors (or if those neighbors don't exist)
Asked in
Google 15 Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen