forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductSum.java
More file actions
42 lines (35 loc) · 966 Bytes
/
ProductSum.java
File metadata and controls
42 lines (35 loc) · 966 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
31
32
33
34
35
36
37
38
39
40
41
42
package algoexpert;
import java.util.ArrayList;
/*
PROBLEM:
[Integer or ArrayList<Object>] -> sum (based on formula)
[x,[y,z,[a]]] -> x + 2y + 2z + 3a
Logic:
go over the array
if int -> add to current Sum
else -> goDeeper(array, multiplier)
Solution:
1. Recursion : T : O(n) | S : O(n)
*/
public class ProductSum {
public static int goDeeper(ArrayList<Object> array, Integer multiplier)
{
int currentSum = 0;
for (Object consider : array){
if (consider instanceof Integer)
{
currentSum += ((Integer)consider * multiplier); // add to sum
}
else
{
// it is an arraylist -> go deeper
currentSum += multiplier * goDeeper((ArrayList<Object>)consider, multiplier + 1);
}
}
return currentSum;
}
public static int productSum(ArrayList<Object> array)
{
return goDeeper(array, 1);
}
}