Skip to content

Commit 85bb78c

Browse files
committed
Add solution #339
1 parent fe9820f commit 85bb78c

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@
327327
336|[Palindrome Pairs](./solutions/0336-palindrome-pairs.js)|Hard|
328328
337|[House Robber III](./solutions/0337-house-robber-iii.js)|Medium|
329329
338|[Counting Bits](./solutions/0338-counting-bits.js)|Easy|
330+
339|[Nested List Weight Sum](./solutions/0339-nested-list-weight-sum.js)|Medium|
330331
341|[Flatten Nested List Iterator](./solutions/0341-flatten-nested-list-iterator.js)|Medium|
331332
342|[Power of Four](./solutions/0342-power-of-four.js)|Easy|
332333
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 339. Nested List Weight Sum
3+
* https://leetcode.com/problems/nested-list-weight-sum/
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 nested
10+
* list [1,[2,2],[[3],2],1] has each integer's value set to its depth.
11+
*
12+
* Return the sum of each integer in nestedList multiplied by its depth.
13+
*/
14+
15+
/**
16+
* @param {NestedInteger[]} nestedList
17+
* @return {number}
18+
*/
19+
var depthSum = function(nestedList) {
20+
return calculateDepth(nestedList, 1);
21+
22+
function calculateDepth(list, depth) {
23+
let total = 0;
24+
for (const element of list) {
25+
if (element.isInteger()) {
26+
total += element.getInteger() * depth;
27+
} else {
28+
total += calculateDepth(element.getList(), depth + 1);
29+
}
30+
}
31+
return total;
32+
}
33+
};

0 commit comments

Comments
 (0)