Optimized Solution for Summing Good Numbers Based on Surrounding k Elements in Array
IntuitionThe goal is to sum up the "good" numbers in the array. A number at index i is considered "good" if:
It's greater than the element at i - k (if that ind
# Intuition
The goal is to sum up the "good" numbers in the array. A number at index `i` is considered "good" if:
- It's greater than the element at `i - k` (if that index exists), **and**
- It's greater than the element at `i + k` (if that index exists).

We handle edge cases where either `i - k` or `i + k` goes out of bounds.

# Approach
1. Loop through each element in the array.
2. For each index `i`, check:
   - If both `i - k` and `i + k` are valid, and the value is greater than both neighbors, add to result.
   - If only `i - k` is valid, check and compare.
   - If only `i + k` is valid, check and compare.
   - If neither is valid (i.e., edge cases), directly add to the result.
3. Return the final sum.

# Complexity
- Time complexity:  
$$O(n)$$ — Single loop through the array.

- Space complexity:  
$$O(1)$$ — No extra space used.

# Code
class Solution {
    public int sumOfGoodNumbers(int[] nums, int k) {
        int n = nums.length, result = 0;
        for(int i = 0; i < n; i++) {
            if(i - k >= 0 && i + k < n) {
                if(nums[i] > nums[i - k] && nums[i] > nums[i + k]) {
                    result += nums[i];
                }
            } else if(i - k >= 0) {
                if(nums[i] > nums[i - k]) {
                    result += nums[i];
                }
            } else if(i + k < n) {
                if(nums[i] > nums[i + k]) {
                    result += nums[i];
                }
            } else {
                result += nums[i]; // when both neighbors are out of bounds
            }
        }
        return result;
    }
}

['Java']