2455. Average Value of Even Numbers That Are Divisible by Three
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:
- Initialize variables
sum
andcount
to 0. - Iterate through each element
num
in the arraynums
. - Check if
num
is even and divisible by 3. - If the condition is satisfied, add
num
tosum
and incrementcount
. - After iterating through all elements, return
sum / count
ifcount
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.