-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductSum.java
More file actions
30 lines (28 loc) · 760 Bytes
/
ProductSum.java
File metadata and controls
30 lines (28 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;
class Program {
// O(n) time | O(h) space - where n is the number of elements in the special
// array and h is the maximum depth
// Tip: You can use `element instanceof ArrayList` to check whether an item
// is an array or an integer.
public static int productSum(List<Object> array) {
// Write your code here.
int sum = 0;
for (Object obj : array) {
sum += calculateSumAtDepth(obj, 1);
System.out.println(sum);
}
return sum;
}
private static int calculateSumAtDepth(Object o, int depth) {
if (o instanceof ArrayList) {
++depth;
int sum = 0;
for (Object obj : (ArrayList) o) {
sum += depth * calculateSumAtDepth(obj, depth);
}
return sum;
} else {
return ((Integer) o).intValue();
}
}
}