LeetCode每日一题(Maximum Product of Splitted Binary Tree)

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.

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)

Example 3:

Input: root = [2,3,9,10,7,8,6,5,4,11,1]
Output: 1025

Example 4:

Input: root = [1,1]
Output: 1

Constraints:

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

这本质是一道数学题:

  1. x + y = k
  2. x * y = x * (k-x) = kx - x²
  3. 当x = k/2的时候, kx - x²的值最大, 别问我怎么推的,凭直觉, 然后左右取值试的,真要推倒的话估计是用微积分,但是当年学的东西早还给老师了,只能这样凑活了。
  4. tree的和是sum, subtree的和越接近sum/2, 这时切除subtree, 两边的乘积最大

代码实现(Rust):

impl Solution {
    fn calc_sum(root: &Option<Rc<RefCell<TreeNode>>>, sums: &mut Vec<i32>) -> i32 {
        if let Some(r) = root {
            let left = Solution::calc_sum(&r.borrow().left, sums);
            let right = Solution::calc_sum(&r.borrow().right, sums);
            let total = r.borrow().val + left + right;
            sums.push(total);
            return total;
        }
        return 0;
    }
    pub fn max_product(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        let mut sums = Vec::new();
        Solution::calc_sum(&root, &mut sums);
        let total = *sums.last().unwrap();
        let mut diff = total;
        let mut half = 0;
        for i in 0..sums.len()-1 {
            if (total - sums[i] * 2).abs() < diff {
                diff = (total - sums[i] * 2).abs();
                half = sums[i];
            }
        }
        (((total - half) as i64 * half as i64) % 1000000007 as i64) as i32
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值