Sum of Good Numbers - Problem

In this problem, you need to identify "good" numbers in an array based on their position and neighboring elements.

Given an array of integers nums and an integer k, an element nums[i] is considered good if:

  • It is strictly greater than the element at index i - k (if that index exists)
  • AND it is strictly greater than the element at index i + k (if that index exists)
  • If neither of these indices exist (i.e., the element is within k positions from both ends), the element is automatically considered good

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

Example: For nums = [1, 2, 3, 4, 5] and k = 2:

  • nums[0] = 1 is good (no element at index -2)
  • nums[1] = 2 is good (no element at index -1)
  • nums[2] = 3 is good if 3 > nums[0] and 3 > nums[4]

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 3, 4, 5], k = 2
โ€บ Output: 4
๐Ÿ’ก Note: Elements 1 and 3 are good. nums[0]=1 (no i-k, no i+k within bounds), nums[2]=3 (3>1 and 3<5, but since one condition fails, it's not good). Actually, nums[0]=1 and nums[1]=2 are good because they don't have valid i-k indices.
example_2.py โ€” All Good Case
$ Input: nums = [5, 4, 3, 2, 1], k = 1
โ€บ Output: 12
๐Ÿ’ก Note: nums[0]=5 (no i-k, 5>4), nums[2]=3 (3>4 false), nums[4]=1 (1>2 false, no i+k). Only boundary elements and elements greater than both neighbors are good.
example_3.py โ€” Edge Case
$ Input: nums = [10], k = 1
โ€บ Output: 10
๐Ÿ’ก Note: Single element with no neighbors at distance k, so it's automatically good.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค k โ‰ค nums.length
  • -109 โ‰ค nums[i] โ‰ค 109
  • nums[i] must be strictly greater than neighbors

Visualization

Tap to expand
Mountain Peak Detection (k=2)31425Hikerk=2 back (4 > 3 โœ“)k=2 forward (4 < 5 โœ—)Analysis:Peak 4 is taller than peak 3 (โœ“) but shorter than peak 5 (โœ—) โ†’ Not GoodGood Peaks: 3 (boundary), 1 (boundary) โ†’ Sum = 4
Understanding the Visualization
1
Survey Position
Stand at current mountain position and look k steps back and forward
2
Compare Heights
Check if current peak is taller than both distant neighbors
3
Handle Boundaries
If you can't see k steps away (edge of range), consider condition satisfied
4
Record Peak
If all conditions met, add this peak's height to your total
Key Takeaway
๐ŸŽฏ Key Insight: We only need one pass through the array, directly accessing k-distance neighbors in O(1) time, making this an optimal O(n) solution.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~12 min Avg. Time
890 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