Running Totals (Scan)
Problem
Print the running totals of an array: the first number, then the sum of the first two numbers, then the sum of the first three, and so on, separated by spaces. Write it in a functional way with a fold (reduce) that carries the total so far.
Constraints
- 1 <= n <= 5000
- |value| <= 10^6
Examples
Input
4 1 2 3 4
Output
1 3 6 10
Solutions
A fold (reduce) gives one final value. A scan gives every step. Python has itertools.accumulate for this. The spread-based JavaScript version copies the array each step, so it is O(n^2); the Java and Python versions are O(n).
/*
* Problem : Running totals.
* Input : n, then n integers.
* Output : n totals.
* Approach: Fold with state.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.*;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: The accumulator is a one-element array that holds the total so far. A lambda cannot change a normal variable.
long[] total = {0};
// Step 2: The stream turns each value into the new running total. mapToInt gives an IntStream again.
return java.util.Arrays.stream(a).map(value -> {
total[0] += value;
return (int) total[0];
}).toArray();
}
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(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- What is the difference between reduce and scan?