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.
This is a classic case of recursion
since we are asked to multiply the nested arrays with their depths
.
The solution is straightforward - as and when we encounter a nested array, we multiply the array sum with the respective depth (increment it when we loop through the nested array).
sum
variable that will keep track of the local sum values. Pass in a depth
parameter that will help us to know what the current depth of the array is during recursion.arr[i]
is NOT AN ARRAY
, we add it to the cummulative sum and at the end return sum * depth
.productSum()
method again by passing depth +1
- Since we are going into a nested array, the depth will increase.sum * depth
at the end.