Variable Number of Arguments
Problem
Write one method that accepts any number of integers (varargs in Java, rest parameters in JavaScript and TypeScript, *args in Python) and gives back their sum, minimum and maximum. Read the numbers, call the method, and print three lines: sum=..., min=..., max=....
Constraints
- 1 <= n <= 10^5
- |value| <= 10^6
Examples
Input
3 3 1 2
Output
sum=6 min=1 max=3
Solutions
A varargs method hides the array from the caller. Only one varargs parameter is allowed and it must be the last parameter. Passing an existing array (a, or *a, or ...a) works in every language.
/*
* Problem : Varargs stats.
* Input : n, then n integers.
* Output : Three lines.
* Approach: One varargs method.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: int... means "any number of ints". Inside the method the values arrive as an int array.
static String[] stats(int... values) {
long sum = 0;
int min = values[0];
int max = values[0];
// Step 2: One pass finds the sum, the smallest and the biggest value.
for (int value : values) {
sum += value;
min = Math.min(min, value);
max = Math.max(max, value);
}
return new String[] {"sum=" + sum, "min=" + min, "max=" + max};
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(int[] a) {
// Step 3: An int[] can be passed to a varargs method directly.
return stats(a);
}
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 must the varargs parameter be last?