#3452

Sum of Good Numbers

Easy
ArrayArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

By iterating through the array once and checking conditions for good numbers, we achieve a more efficient solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a sum variable to 0.
  2. 2Step 2: Loop through each index i in nums.
  3. 3Step 3: Check if nums[i] is greater than its neighbors at i - k and i + k, adding to sum if true.
solution.py6 lines
1def sum_of_good_numbers(nums, k):
2    total = 0
3    for i in range(len(nums)):
4        if (i < k or nums[i] > nums[i - k]) and (i + k >= len(nums) or nums[i] > nums[i + k]):
5            total += nums[i]
6    return total

Complexity note: We only pass through the array once, checking conditions in constant time.

  • 1Good numbers can be at the edges of the array without neighbors.
  • 2Checking both neighbors is crucial for determining goodness.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.