Given an array (that can have nested arrays) - return the sum of all the numbers in the array. If nested array is encountered, recursively add the numbers in the nested array multiplied by the depth of the nested array.
Input: [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
Output: 12
If we encounter a non nested
value - we simply add it to the global sum. If we encounter a nested array
, the sum inside of the nested array is multiplied with the depth
of that array and then returned.
So the array [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
becomes:
Equation = (5 + 2 + (7 - 1) * 2 + 3 + (6 + (-13 + 8)*3 + 4)*2) * 1
= 12
Click to reveal
Recursion is your best friend. 💯
Click to reveal
Can you keep track of the depth using recursion? Can a helper function help you with this where you can pass in the depth initialized to 1
?