LeetCode 3452: Sum of Good Numbers Solution

Master LeetCode problem 3452 (Sum of Good Numbers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3452. Sum of Good Numbers

Easy

Problem Explanation

Explanation:

To solve this problem, we can iterate over the array nums and for each element at index i, check if it is strictly greater than the elements at indices i - k and i + k (if they exist). If either of these indices does not exist, we consider the element good as well. We can keep track of the sum of all good elements and return this sum as the final result.

Algorithm:

  1. Initialize a variable sum to store the sum of good elements.
  2. Iterate over the array nums from index 0 to n - 1 where n is the length of nums.
  3. For each element nums[i], check if it is strictly greater than nums[i - k] and nums[i + k] (if they exist).
  4. If the condition is satisfied or either of the indices does not exist, add nums[i] to sum.
  5. Return the final sum as the result.

Time Complexity: O(n), where n is the length of the input array nums. Space Complexity: O(1).

:

Solution Code

class Solution {
    public int sumOfGoodNumbers(int[] nums, int k) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            boolean good = true;
            if (i - k >= 0 && nums[i] <= nums[i - k]) {
                good = false;
            }
            if (i + k < nums.length && nums[i] <= nums[i + k]) {
                good = false;
            }
            if (good) {
                sum += nums[i];
            }
        }
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3452 (Sum of Good Numbers)?

This page provides optimized solutions for LeetCode problem 3452 (Sum of Good Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3452 (Sum of Good Numbers)?

The time complexity for LeetCode 3452 (Sum of Good Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3452 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3452 in Java, C++, or Python.

Back to LeetCode Solutions