Skip to content

Commit 7884591

Browse files
committed
Add solution #1339
1 parent 2624c95 commit 7884591

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,239 LeetCode solutions in JavaScript
1+
# 1,240 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1016,6 +1016,7 @@
10161016
1335|[Minimum Difficulty of a Job Schedule](./solutions/1335-minimum-difficulty-of-a-job-schedule.js)|Hard|
10171017
1337|[The K Weakest Rows in a Matrix](./solutions/1337-the-k-weakest-rows-in-a-matrix.js)|Easy|
10181018
1338|[Reduce Array Size to The Half](./solutions/1338-reduce-array-size-to-the-half.js)|Medium|
1019+
1339|[Maximum Product of Splitted Binary Tree](./solutions/1339-maximum-product-of-splitted-binary-tree.js)|Medium|
10191020
1342|[Number of Steps to Reduce a Number to Zero](./solutions/1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy|
10201021
1351|[Count Negative Numbers in a Sorted Matrix](./solutions/1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy|
10211022
1352|[Product of the Last K Numbers](./solutions/1352-product-of-the-last-k-numbers.js)|Medium|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 1339. Maximum Product of Splitted Binary Tree
3+
* https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, split the binary tree into two subtrees by removing one edge
7+
* such that the product of the sums of the subtrees is maximized.
8+
*
9+
* Return the maximum product of the sums of the two subtrees. Since the answer may be too large,
10+
* return it modulo 109 + 7.
11+
*
12+
* Note that you need to maximize the answer before taking the mod and not after taking it.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @return {number}
26+
*/
27+
var maxProduct = function(root) {
28+
const sums = [];
29+
const MOD = 1e9 + 7;
30+
const total = calculateSum(root);
31+
let maxProd = 0;
32+
33+
for (const sum of sums) {
34+
maxProd = Math.max(maxProd, sum * (total - sum));
35+
}
36+
37+
return maxProd % MOD;
38+
39+
function calculateSum(node) {
40+
if (!node) return 0;
41+
const leftSum = calculateSum(node.left);
42+
const rightSum = calculateSum(node.right);
43+
const totalSum = node.val + leftSum + rightSum;
44+
sums.push(totalSum);
45+
return totalSum;
46+
}
47+
};

0 commit comments

Comments
 (0)