Skip to content

Commit 51b3132

Browse files
authored
Create 2538-difference-between-maximum-and-minimum-price-sum.js
1 parent 5818704 commit 51b3132

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number[]} price
5+
* @return {number}
6+
*/
7+
const maxOutput = function(n, edges, price) {
8+
const tree = [];
9+
const memo = [];
10+
for (let i = 0; i < n; i++) tree[i] = [];
11+
for (const [a, b] of edges) {
12+
tree[a].push(b);
13+
tree[b].push(a);
14+
}
15+
16+
let result = 0;
17+
dfs(0, -1);
18+
19+
function dfs(node, parent) {
20+
const max = [price[node], 0];
21+
const nodes = tree[node] ?? [];
22+
for (const child of nodes) {
23+
if (child === parent) continue;
24+
const sub = dfs(child, node);
25+
result = Math.max(result, max[0] + sub[1]);
26+
result = Math.max(result, max[1] + sub[0]);
27+
max[0] = Math.max(max[0], sub[0] + price[node]);
28+
max[1] = Math.max(max[1], sub[1] + price[node]);
29+
}
30+
return max;
31+
}
32+
33+
return result;
34+
};

0 commit comments

Comments
 (0)