e.g.#1
[1, 1, 1, 2, 22, 35, 35, 120, 320]
==>> [3, 2, 22, 70, 120, 320]
note how repeated consecutive 1\'s and 35\'s are coalesced to 3 and 70
Here is an approach using a stack.
public static List coalesce(List list) {
Stack stack = new Stack<>();
stack.addAll(list);
List sums = new ArrayList<>();
int sum = 0;
while (!stack.isEmpty()) {
int val = stack.pop();
sum += val;
if (!stack.isEmpty() && stack.peek() != val) {
sums.add(0,sum);
sum = 0;
}
}
sums.add(0,sum);
return sums;
}