首页 > 其他 > 详细

[LC] 1167. Minimum Cost to Connect Sticks

时间:2020-04-16 11:03:45      阅读:63      评论:0      收藏:0      [点我收藏+]

You have some sticks with positive integer lengths.

You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y.  You perform this action until there is one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

 

Example 1:

Input: sticks = [2,4,3]
Output: 14

Example 2:

Input: sticks = [1,8,3,5]
Output: 30

 

class Solution {
    public int connectSticks(int[] sticks) {
        // Arrays.sort(sticks);
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int num : sticks) {
            pq.offer(num);
        }
        int res = 0;
        while (pq.size() > 1) {
            int sum = pq.poll() + pq.poll();
            pq.offer(sum);
            res += sum;
        }
        return res;
    }
}

 

[LC] 1167. Minimum Cost to Connect Sticks

原文:https://www.cnblogs.com/xuanlu/p/12711203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!