3452. Sum of Good Numbers LeetCode Solution

In this guide, you will get 3452. Sum of Good Numbers LeetCode Solution with the best time and space complexity. The solution to Sum of Good Numbers problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum of Good Numbers solution in C++
  4. Sum of Good Numbers solution in Java
  5. Sum of Good Numbers solution in Python
  6. Additional Resources
3452. Sum of Good Numbers LeetCode Solution image

Problem Statement of Sum of Good Numbers

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 <= 100
1 <= nums[i] <= 1000
1 <= k <= floor(nums.length / 2)

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3452. Sum of Good Numbers LeetCode Solution in C++

class Solution {
 public:
  int sumOfGoodNumbers(vector<int>& nums, int k) {
    const int n = nums.size();
    int sum = 0;

    for (int i = 0; i < n; ++i)
      if ((i - k < 0 || nums[i] > nums[i - k]) &&
          (i + k >= n || nums[i] > nums[i + k]))
        sum += nums[i];

    return sum;
  }
};
/* code provided by PROGIEZ */

3452. Sum of Good Numbers LeetCode Solution in Java

class Solution {
  public int sumOfGoodNumbers(int[] nums, int k) {
    final int n = nums.length;
    int sum = 0;

    for (int i = 0; i < n; ++i)
      if ((i - k < 0 || nums[i] > nums[i - k]) && //
          (i + k >= n || nums[i] > nums[i + k]))
        sum += nums[i];

    return sum;
  }
}
// code provided by PROGIEZ

3452. Sum of Good Numbers LeetCode Solution in Python

class Solution:
  def sumOfGoodNumbers(self, nums: list[int], k: int) -> int:
    return sum(num for i, num in enumerate(nums)
               if (i - k < 0 or num > nums[i - k])
               and (i + k >= len(nums) or num > nums[i + k]))
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.