Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sum Of Good Numbers

Count the elements in an array that are strictly greater than their nearby neighbors.

Acceptance 0%
Problem Statement

Given an integer array, identify the elements that are considered good based on their surrounding values. An element is good if it is strictly greater than the elements that are k positions to its left and k positions to its right, whenever those neighbors exist. Return the sum of all good elements.

In other words, for each index i, check whether:

  • i - k >= 0 implies nums[i] > nums[i-k]
  • i + k < n implies nums[i] > nums[i+k]

If both conditions hold, include nums[i] in the final sum.

Input Format

  • An integer array nums
  • An integer k

Output Format

  • Return a single integer: the sum of all good numbers in nums.

Constraints

  • 1 <= nums.length
  • k >= 1
  • Compare only values at distance exactly k
  • If a required neighbor does not exist, ignore that side of the check
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,3,2,1,5,4], k = 2

Output

8

Explanation

The good numbers are 3 and 5.

  • 3 is greater than nums[0] = 1 and nums[4] = 5? No, so in this example it would not qualify under the exact distance-k rule.

Illustrative corrected example: nums = [2,5,3,9,6,7], k = 1 Good numbers are 5, 9, and 7, so the sum is 21.

Example 2

Input

nums = [10,4,6,3,8], k = 2

Output

14

Explanation

Check each index against neighbors two positions away.

  • 6 is greater than 10? No.
  • 3 is greater than 4 and 8? No.
  • 8 has only a left neighbor at distance 2, which is 6, and 8 > 6, so 8 is good.
  • 4 has only a right neighbor at distance 2, which is 3, and 4 > 3, so 4 is good. Sum = 4 + 8 = 12.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.