Skip to content

Commit 7171461

Browse files
committed
Add solution #364
1 parent 4d1dac8 commit 7171461

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@
352352
361|[Bomb Enemy](./solutions/0361-bomb-enemy.js)|Medium|
353353
362|[Design Hit Counter](./solutions/0362-design-hit-counter.js)|Medium|
354354
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
355+
364|[Nested List Weight Sum II](./solutions/0364-nested-list-weight-sum-ii.js)|Medium|
355356
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
356357
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
357358
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)