Skip to content

Commit 67c3ac2

Browse files
authored
Update 1167-minimum-cost-to-connect-sticks.js
1 parent 694b116 commit 67c3ac2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

1167-minimum-cost-to-connect-sticks.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
1+
/**
2+
3+
You have some sticks with positive integer lengths.
4+
5+
You can connect any two sticks of lengths X and Y into
6+
one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.
7+
8+
Return the minimum cost of connecting all the given sticks into one stick in this way.
9+
10+
Example 1:
11+
12+
Input: sticks = [2,4,3]
13+
Output: 14
14+
Example 2:
15+
16+
Input: sticks = [1,8,3,5]
17+
Output: 30
18+
19+
Constraints:
20+
21+
1 <= sticks.length <= 10^4
22+
1 <= sticks[i] <= 10^4
23+
24+
*/
25+
126
/**
227
* @param {number[]} sticks
328
* @return {number}
@@ -40,3 +65,32 @@ const swap = (arr, i, j) => {
4065
arr[i] = arr[j]
4166
arr[j] = temp
4267
}
68+
69+
// another
70+
71+
/**
72+
* @param {number[]} sticks
73+
* @return {number}
74+
*/
75+
const connectSticks = function(sticks) {
76+
if (sticks.length === 1) return 0
77+
sticks.sort((a, b) => a - b)
78+
let sum = [],
79+
result = 0
80+
while (sticks.length || sum.length > 1) {
81+
let cur = 0
82+
for (let i = 0; i < 2; i++) {
83+
if (sticks[0] && (sum[0] === undefined || sticks[0] < sum[0])) {
84+
cur += sticks[0]
85+
sticks.shift()
86+
} else {
87+
cur += sum[0]
88+
sum.shift()
89+
}
90+
}
91+
sum.push(cur)
92+
result += cur
93+
}
94+
return result
95+
}
96+

0 commit comments

Comments
 (0)