Skip to content

Commit 8ff35e6

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

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,34 @@ const connectSticks = function(sticks) {
9494
return result
9595
}
9696

97+
// another
98+
99+
/**
100+
* @param {number[]} sticks
101+
* @return {number}
102+
*/
103+
const connectSticks = function(sticks) {
104+
sticks.sort((a, b) => a - b)
105+
const sums = []
106+
let result = 0
107+
if (sticks.length < 2) return result
108+
const getMin = () => {
109+
const stick = sticks.length ? sticks[0] : Infinity
110+
const sum = sums.length ? sums[0] : Infinity
111+
if (sum < stick) {
112+
return sums.shift()
113+
} else {
114+
return sticks.shift()
115+
}
116+
}
117+
while (sticks.length || sums.length > 1) {
118+
const tmp1 = getMin()
119+
const tmp2 = getMin()
120+
const curr = tmp1 + tmp2
121+
result += curr
122+
sums.push(curr)
123+
}
124+
return result
125+
}
126+
127+

0 commit comments

Comments
 (0)