# 1167. Minimum Cost to Connect Sticks

```
T: O(nlogn)
S: O(n)
```

```
class Solution {
    public int connectSticks(int[] sticks) {
        int n = sticks.length;
        if (n == 1 || n == 0) {
            return 0;
        }
        Queue<Integer> pq = new PriorityQueue<>();
        
        for (int i = 0; i < n; i++) {
            pq.offer(sticks[i]);
        }
        
        int cost = 0;
        while (!pq.isEmpty()) {
            int num = 0;
            if (!pq.isEmpty()) {
                num = pq.poll();
            }
            int num2 = 0;
            if (!pq.isEmpty()) {
                num2 = pq.poll();
            }
            int newCost = num + num2;
            cost += newCost;
            pq.offer(newCost);
            if (pq.size() == 1) {
                break;
            }
        }
        
        return cost;
    }
}

/*
[1,8,3,5]

1 3

greedy thinking + pq

一定從小的來接, cost 最小,
所以可以用一個 pq, 來放值
然後加完後的 cost 再丟回去 pq
依照這版邏輯, 最後 pq 會剩下只有一個結果（cost) 時要跳出

T: O(nlogn)
S: O(n)
*/
```

## more simpler

change to&#x20;

```
while (pq.size() > 1) {
```

then don't need worry about pq.poll is empty()

```java
class Solution {
    public int connectSticks(int[] sticks) {
        int n = sticks.length;
        if (n == 1 || n == 0) {
            return 0;
        }
        Queue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < n; i++) {
            pq.offer(sticks[i]);
        }
        
        int cost = 0;
        while (pq.size() > 1) {
            int newCost = pq.poll() + pq.poll();
            cost += newCost;
            pq.offer(newCost);
        }
        
        return cost;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/1167.-minimum-cost-to-connect-sticks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
