Average of the Positive Numbers
Problem
Print the whole-number average of the positive numbers in the array (the sum divided by the count, rounded down). Zero and negative numbers are ignored. If there is no positive number, print none (think of it as an empty Optional).
Constraints
- 1 <= n <= 10^5
Examples
Input
4 -5 10 20 -30
Output
15
Solutions
Filter the positive numbers, then reduce them to a count and a sum. An empty result is an explicit case (Optional.empty in Java), not a fake number like 0 or -1.
/*
* Problem : Average of positives.
* Input : n, then n integers.
* Output : The average or none.
* Approach: Filter and reduce.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(int[] a) {
// Step 1: Keep the positive numbers. The stream gives a summary with count and sum.
java.util.LongSummaryStatistics stats = java.util.Arrays.stream(a).filter(v -> v > 0).asLongStream().summaryStatistics();
// Step 2: With no positive number there is no answer. Optional models "no value" without a special number.
java.util.Optional<Long> average = stats.getCount() == 0 ? java.util.Optional.<Long>empty() : java.util.Optional.of(stats.getSum() / stats.getCount());
return average.map(String::valueOf).orElse("none");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (2)
- Why is 0 a bad answer for 'no positives'?
- What do filter and reduce each do?