[LeetCode] 1167. Minimum Cost to Connect Sticks

You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.

You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only 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
Explanation: You start with sticks = [2,4,3].
1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4].
2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9].
There is only one stick left, so you are done. The total cost is 5 + 9 = 14.

Example 2:

Input: sticks = [1,8,3,5]
Output: 30
Explanation: You start with sticks = [1,8,3,5].
1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5].
2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8].
3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17].
There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.

Example 3:

Input: sticks = [5]
Output: 0
Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.

Constraints:

  • 1 <= sticks.length <= 104
  • 1 <= sticks[i] <= 104

连接棒材的最低费用。

为了装修新房,你需要加工一些长度为正整数的棒材 。棒材以数组 sticks 的形式给出,其中 sticks[i] 是第 i 根棒材的长度。

如果要将长度分别为 x 和 y 的两根棒材连接在一起,你需要支付 x + y 的费用。 由于施工需要,你必须将所有棒材连接成一根。

返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-cost-to-connect-sticks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是贪心。题目指出连接棒材的费用是两个棒材的长度之和,同时因为题目最终要达到的目的是把 input 中所有的棒材连接在一起,所以做法应该是优先找长度最短的两根棒材连接,这样连接的费用始终是input中长度最短的两根棒材的长度之和。

时间O(nlogn)

空间O(n)

Java实现

 1 class Solution {
 2     public int connectSticks(int[] sticks) {
 3         PriorityQueue<Integer> queue = new PriorityQueue<>();
 4         for (int s : sticks) {
 5             queue.offer(s);
 6         }
 7         int sum = 0;
 8         while (queue.size() > 1) {
 9             int first = queue.poll();
10             int second = queue.poll();
11             sum += first + second;
12             queue.offer(first + second);
13         }
14         return sum;
15     }
16 }

 

LeetCode 题目总结

上一篇:Sobel边缘检测


下一篇:算法题:连接棒材的最低费用