.Zzumbong

[leetCode/JS] 1339. Maximum Product of Splitted Binary Tree ๋ณธ๋ฌธ

coding test/leetCode

[leetCode/JS] 1339. Maximum Product of Splitted Binary Tree

์ญ˜๋ด‰ 2022. 12. 10. 15:30

๋‚œ์ด๋„ [ ๐Ÿค” ] Medium

๋ฌธ์ œ ์„ค๋ช…

Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.

Return the maximum product of the sums of the two subtrees. Since the answer may be too large,

return it modulo 109 + 7.

Note that you need to maximize the answer before taking the mod and not after taking it.

 

๋ฌธ์ œ๊ฐ€ ์ข€ ๋ณต์žกํ•œ๋ฐ, ์š”์•ฝํ•˜์ž๋ฉด
ํ•˜๋‚˜์˜ ์ด์ง„ํŠธ๋ฆฌ๋ฅผ 2๊ฐœ๋กœ ๋‚˜๋ˆ ์„œ ๊ฐ๊ฐ ํŠธ๋ฆฌ์˜ ํ•ฉ๊ณ„์˜ ๊ณฑ์ด ๊ฐ€์žฅ ํฐ ์ˆซ์ž๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

 

์ž…์ถœ๋ ฅ ์˜ˆ

Example 1:

Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

 

 

Example 2:

 

Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)

 

Constraints

  • The number of nodes in the tree is in the range [2, 5 * 104].
  • 1 <= Node.val <= 104

 

 


 

 

๋‚ด ์†”๋ฃจ์…˜

  • ์˜ˆ์ œ1๋กœ ์„ค๋ช…ํ•˜์ž๋ฉด [1, 2, 3, 4, 5, 6]๋ฅผ DFS๋กœ ๋Œ๋ ค์„œ [4, 5, 2, 6, 3, 1] ์ˆœ์„œ๋กœ ์„œ์น˜ํ•œ๋‹ค.
  • ํ•˜์œ„ ๋…ธ๋“œ๋ถ€ํ„ฐ ๋Œ๋ฉด์„œ ์ž๋ฅผ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ž˜๋ผ์„œ sums์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค
  • sums = [4, 5, 11, 6, 9, 21]๋กœ ์ž˜๋ผ์ง„ ๋…ธ๋“œ์˜ ํ•ฉ๊ณ„๋ฅผ sums์— ์ €์žฅํ•œ๋‹ค.

์ด๋Ÿฐ ๋Š๋‚Œ์œผ๋กœ ์ž˜๋ผ์„œ ์ž˜๋ฆฐ ํŠธ๋ฆฌ์˜ sum์„ ์ €์žฅํ•œ๋‹ค.

  • ๋งˆ์ง€๋ง‰์œผ๋กœ sum์€ ์ €์žฅ๋œ(์ž˜๋ฆฐ) ํŠธ๋ฆฌ์˜ ํ•ฉ๊ณ„์™€ ๋‚˜๋จธ์ง€ (total-sum)์„ ๊ณฑํ•ด์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ returnํ•˜๋ฉด ๋๋‚œ๋‹ค.
var maxProduct = function(root) {
  const sums = [];
  const dfs = (node) => {
    if(!node) return 0;
    const sum = node.val + dfs(node.left) + dfs(node.right);
    sums.push(sum);
    return sum;
  }
  const total = dfs(root);
  return Math.max(...sums.map(s => (total - s) * s)) % (1e9 + 7);
};

 

๊ฐ์ƒํ‰

  • DFS ํŒŒํ‹ฐ๊ตฌ๋‚˜ ์ƒ์†Œํ•œ ๋ฌธ์ œ์˜€๋‹ค. ์žฌ๋ฏธ์žˆ์–ด

'coding test > leetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[leetCode/JS] 70. Climbing Stairs  (0) 2022.12.12
[leetCode/JS] 124. Binary Tree Maximum Path Sum  (0) 2022.12.11
[leetCode/JS] 1026. Maximum Difference Between Node and Ancestor  (0) 2022.12.09
[leetCode/JS] 872. Leaf-Similar Trees  (0) 2022.12.08
[leetCode/JS] 938. Range Sum of BST  (0) 2022.12.07
0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ