Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2455. Average Value of Even Numbers That Are Divisible by Three

ArrayMath

Explanation:

To solve this problem, we iterate through the given array nums and check if each even number is divisible by 3. If it is, we add it to our running sum and keep track of the count of such numbers. Finally, we return the integer division of the sum by the count. If no even number is found that satisfies the condition, we return 0.

Algorithm:

  1. Initialize variables sum and count to 0.
  2. Iterate through each element num in the array nums.
  3. Check if num is even and divisible by 3.
  4. If the condition is satisfied, add num to sum and increment count.
  5. After iterating through all elements, return sum / count if count is greater than 0, else return 0.

Time Complexity: O(n), where n is the number of elements in the input array. Space Complexity: O(1)

:

class Solution {
    public int averageEvenDivByThree(int[] nums) {
        int sum = 0;
        int count = 0;
        
        for (int num : nums) {
            if (num % 2 == 0 && num % 3 == 0) {
                sum += num;
                count++;
            }
        }
        
        return count > 0 ? sum / count : 0;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.