Summary Statistics in One Pass
Problem
Print five lines for an array: count=, sum=, min=, max= and average=. The average is the sum divided by the count, rounded down toward negative infinity (floor). Compute all values in ONE pass over the numbers with a single fold (reduce) that carries a small state, or with the library helper for statistics.
Constraints
- 1 <= n <= 10^5
- |value| <= 10^6
Examples
Input
3 4 8 15
Output
count=3 sum=27 min=4 max=15 average=9
Solutions
Computing sum, min and max in three separate loops reads the data three times. One fold with a small state reads it once, which matters for big files or streams. Java's IntSummaryStatistics does exactly this. Use floor division for negatives: -5 / 2 is -3 with floor and -2 when it is cut toward zero.
/*
* Problem : Five statistics.
* Input : n, then n integers.
* Output : Five lines.
* Approach: One fold.
* 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: IntSummaryStatistics collects count, sum, min and max in one pass over the stream.
java.util.IntSummaryStatistics stats = java.util.Arrays.stream(a).summaryStatistics();
// Step 2: The library average is a double. For a whole-number floor we divide the sum ourselves.
long average = Math.floorDiv(stats.getSum(), stats.getCount());
return new String[] {
"count=" + stats.getCount(),
"sum=" + stats.getSum(),
"min=" + stats.getMin(),
"max=" + stats.getMax(),
"average=" + average
};
}
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(String.join("\n", solve(a)));
}
}
Hints (1)
- Why is one pass better than three loops for a data stream?