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
kpositions 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] = 1is good (no element at index -2)nums[1] = 2is good (no element at index -1)nums[2] = 3is good if3 > nums[0]and3 > 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code