We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 67c3ac2 commit 8ff35e6Copy full SHA for 8ff35e6
1167-minimum-cost-to-connect-sticks.js
@@ -94,3 +94,34 @@ const connectSticks = function(sticks) {
94
return result
95
}
96
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