Optimal One-Pass Solution — Beats 100% | 0ms Runtime
IntuitionThe problem is about identifying "good" elements in an array based on their relation to elements at positions i - k and i + k. An element is good if it
# Intuition
The problem is about identifying "good" elements in an array based on their relation to elements at positions `i - k` and `i + k`. An element is good if it is strictly greater than both of those values **if they exist**, or it is automatically considered good if **neither of them exist**. My initial thought was to use a simple loop and conditional checks to determine the existence of the neighboring indices.

# Approach
1. Loop through the array from index `0` to `n - 1`.
2. For each index `i`, check if both `i - k` and `i + k` are within the array bounds:
   - If both exist: check if `nums[i]` is greater than both `nums[i - k]` and `nums[i + k]`.
   - If only one exists: compare `nums[i]` with the one that exists.
   - If neither exists: the element is automatically good.
3. Store all good elements in an array.
4. Return the sum of the good elements using `reduce`.

# Complexity
- Time complexity:  
  $$O(n)$$ — We loop through the entire array once and perform constant-time operations per element.

- Space complexity:  
  $$O(n)$$ — In the worst case, all elements might be "good", and we store them in a separate array before summing them.

# Code
```javascript
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var sumOfGoodNumbers = function(nums, k) {

    let goodPair = []
    let n = nums.length

    for(let i = 0; i < n; i++){
        if(i - k >= 0 && i + k < n){
            if(nums[i] > nums[i - k] && nums[i] > nums[i + k]){
                goodPair.push(nums[i])
            }
        }else if(i - k >= 0){
            if(nums[i] > nums[i - k]){
                goodPair.push(nums[i])
            }
        }else if(i + k < n){
            if(nums[i] > nums[i + k]){
                goodPair.push(nums[i])
            }
        }else {
            // Neither index exists
            goodPair.push(nums[i])
        }
    }

    return goodPair.reduce((acc, val) => acc + val, 0)
};
['Array', 'JavaScript']