当前位置: 首页 > news >正文

LeetCode每日一题2673. Make Costs of Paths Equal in a Binary Tree

文章目录

    • 一、题目
    • 二、题解

一、题目

You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.

Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.

Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.

Note:

A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
The cost of a path is the sum of costs of nodes in the path.

Example 1:

Input: n = 7, cost = [1,5,2,2,3,3,1]
Output: 6
Explanation: We can do the following increments:

  • Increase the cost of node 4 one time.
  • Increase the cost of node 3 three times.
  • Increase the cost of node 7 two times.
    Each path from the root to a leaf will have a total cost of 9.
    The total increments we did is 1 + 3 + 2 = 6.
    It can be shown that this is the minimum answer we can achieve.
    Example 2:

Input: n = 3, cost = [5,3,3]
Output: 0
Explanation: The two paths already have equal total costs, so no increments are needed.

Constraints:

3 <= n <= 105
n + 1 is a power of 2
cost.length == n
1 <= cost[i] <= 104

二、题解

class Solution {
public:int minIncrements(int n, vector<int>& cost) {int res = 0;for(int i = n / 2;i > 0;i--){res += abs(cost[i * 2 - 1] - cost[i * 2]);cost[i - 1] += max(cost[i * 2 - 1],cost[i * 2]);}return res;}
};
http://www.lryc.cn/news/308263.html

相关文章:

  • 贝叶斯分类器
  • 游戏服务之会话管理
  • LeetCode20 有效的括号
  • sql实战_基于某推荐比值问题
  • 协议的概念+本质+作用+最终表现形式,网络问题(技术+应用+解决的协议+存在原因),主机的对称性
  • iOS中卡顿产生的主要原因及优化思路
  • spring boot集成Elasticsearch 7.16.3
  • HTML5+CSS3小实例:环绕小球弹性loading动画
  • SpringBoot 自定义注解实现操作日志记录
  • ubuntu常见配置
  • electron+vue3全家桶+vite项目搭建【27】封装窗口工具类【1】雏形
  • 从模型到复合AI系统的转变
  • 将仓库A中的部分提交迁移到仓库B中
  • 信息安全技术基础
  • flask知识--01
  • 软考52-上午题-【数据库】-关系模式2
  • devc++跑酷小游戏3.5.0
  • Redisson限流算法
  • GPT与MBR:硬盘分区表格式的革新与区别
  • 机器学习-1
  • Stream流详解
  • javaweb学习(day05-TomCat)
  • 【Unity】构建简单实用的年份选择器(简单原理示范)
  • LeetCode 2120.执行所有后缀指令
  • 租赁小程序|租赁系统|租赁软件开发带来高效运营
  • 大数据集群管理软件 CDH、Ambari、DataSophon 对比
  • 插值、逼近、拟合、光顺
  • Java单元测试 - mock静态方法
  • Unity使用PlayableAPI 动态播放动画
  • unity使用Registry类将指定内容写入注册表