Inverse-Depth Weighted Sum of a Nested Integer List
A nested value is either an integer or a list of nested values. You are given a top-level list of nested values. Return the sum of every integer multiplied by an inverse-depth weight: integers at the maximum depth have weight 1, integers one level above them have weight 2, and so on.
Implement inverseDepthSum(nestedList).
Input and Output
-
The top-level list is at depth
1
.
-
The maximum depth is the greatest depth containing an integer. Empty lists do not increase it by themselves.
-
An integer at depth
d
has weight
maximumDepth - d + 1
.
-
Return the weighted sum as a signed 64-bit integer.
Constraints
-
The input contains at most
50,000
integers and list nodes combined.
-
Nesting depth is at most
1,000
.
-
Each integer is in
[-100,000, 100,000]
.
-
The top-level list contains at least one integer somewhere within it.
-
The final weighted sum fits in a signed 64-bit integer.
Example 1
Input: nestedList = [[1, 1], 2, [1, 1]]
Output: 8
The four 1 values have weight 1, and 2 has weight 2.
Example 2
Input: nestedList = [1, [4, [6]]]
Output: 17
The maximum depth is 3, so the sum is 1 * 3 + 4 * 2 + 6 * 1.