Notice
Recent Posts
Recent Comments
Link
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- ๋ง์ง
- ๊ฒ์
- ์ ํฌ๋ธ
- ์ฝํ
- ์ ์ค
- ๋์ซ
- ์ ์ค์๋ด
- ์ก๋ฆฌ๋จ
- ํ์ค์คํค
- ์ ์ฅ
- ์ฝ๋ฉํ ์คํธ
- LeetCode
- ์๊ณ ๋ฆฌ์ฆ
- javascript
- ์กํ
- Sort
- ์ฐ์ฃผ
Archives
- Today
- Total
.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์ ์ ์ฅ๋(์๋ฆฐ) ํธ๋ฆฌ์ ํฉ๊ณ์ ๋๋จธ์ง (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 |
Comments