Sum of Good Numbers Problem
#3452
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3452.
Given an array of integers nums and an integer k, an element nums[i] is considered good if it is strictly greater than the elements at indices i - k and i + k (if those indices exist). If neither of these indices exists, nums[i] is still considered good.
Return the sum of all the good elements in the array.
Example 1:
Input: nums = [1,3,2,1,5,4], k = 2
Output: 12
Explanation:
The good numbers are nums[1] = 3, nums[4] = 5, and nums[5] = 4 because they are strictly greater than the numbers at indices i - k and i + k.
Example 2:
Input: nums = [2,1], k = 1
Output: 2
Explanation:
The only good number is nums[0] = 2 because it is strictly greater than nums[1].
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 10001 <= k <= floor(nums.length / 2)
Solution
Approach: Direct Check
An element is good when it is strictly larger than the element k places before it and the element k places after it, whenever those exist.
Walk through the array. For index i, discard nums[i] if i >= k and nums[i] <= nums[i - k], or if i + k < n and nums[i] <= nums[i + k]. Every other element is good, so add it to the sum.
Complexity: O(n) time and O(1) extra space.
class Solution:
def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
ans = 0
for i, x in enumerate(nums):
if i >= k and x <= nums[i - k]:
continue
if i + k < len(nums) and x <= nums[i + k]:
continue
ans += x
return ans