Nested List Weight Sum II
Description
null
Solution(javascript)
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* function NestedInteger() {
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* @return {boolean}
* this.isInteger = function() {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* @return {integer}
* this.getInteger = function() {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* @return {void}
* this.setInteger = function(value) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
* @return {void}
* this.add = function(elem) {
* ...
* };
*
* Return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer
* @return {NestedInteger[]}
* this.getList = function() {
* ...
* };
* };
*/
/**
* @param {NestedInteger[]} nestedList
* @return {number}
*/
const depthSumInverse = function (nestedList) {
const aux = (nested, depth = 1) => {
if (nested.isInteger()) {
return depth
}
return nested.getList().reduce((acc, current) => Math.max(acc, aux(current, depth + 1)), 0)
}
const maxDepth = nestedList.reduce((acc, nested) => Math.max(acc, aux(nested, 1)), 0)
const aux2 = (nested, depth = 1) => {
if (nested.isInteger()) {
return nested.getInteger() * depth
}
return nested.getList().reduce((acc, current) => acc + aux2(current, depth - 1), 0)
}
return nestedList.reduce((acc, nested) => acc + aux2(nested, maxDepth), 0)
}