|
| 1 | +/** |
| 2 | + * 364. Nested List Weight Sum II |
| 3 | + * https://leetcode.com/problems/nested-list-weight-sum-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a nested list of integers nestedList. Each element is either an integer or |
| 7 | + * a list whose elements may also be integers or other lists. |
| 8 | + * |
| 9 | + * The depth of an integer is the number of lists that it is inside of. For example, the |
| 10 | + * nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Let maxDepth |
| 11 | + * be the maximum depth of any integer. |
| 12 | + * |
| 13 | + * The weight of an integer is maxDepth - (the depth of the integer) + 1. |
| 14 | + * |
| 15 | + * Return the sum of each integer in nestedList multiplied by its weight. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {NestedInteger[]} nestedList |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var depthSumInverse = function(nestedList) { |
| 23 | + const maxDepth = findMaxDepth(nestedList, 1); |
| 24 | + return calculateSum(nestedList, 1, maxDepth); |
| 25 | + |
| 26 | + function findMaxDepth(list, depth) { |
| 27 | + let maxDepth = depth; |
| 28 | + for (const element of list) { |
| 29 | + if (!element.isInteger()) { |
| 30 | + maxDepth = Math.max(maxDepth, findMaxDepth(element.getList(), depth + 1)); |
| 31 | + } |
| 32 | + } |
| 33 | + return maxDepth; |
| 34 | + } |
| 35 | + |
| 36 | + function calculateSum(list, depth, maxDepth) { |
| 37 | + let total = 0; |
| 38 | + for (const element of list) { |
| 39 | + if (element.isInteger()) { |
| 40 | + total += element.getInteger() * (maxDepth - depth + 1); |
| 41 | + } else { |
| 42 | + total += calculateSum(element.getList(), depth + 1, maxDepth); |
| 43 | + } |
| 44 | + } |
| 45 | + return total; |
| 46 | + } |
| 47 | +}; |
0 commit comments