Skip to content

Commit 6b16af1

Browse files
authored
Update 1383-maximum-performance-of-a-team.js
1 parent 69b5699 commit 6b16af1

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

1383-maximum-performance-of-a-team.js

+79
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,82 @@ function moveDown(arr, i, comparator) {
8080
moveDown(arr, next, comparator)
8181
}
8282
}
83+
84+
85+
// another
86+
87+
const MinHeap = () => {
88+
const list = []
89+
const parent = (index) => Math.floor((index - 1) / 2)
90+
const left = (index) => 2 * index + 1
91+
const right = (index) => 2 * index + 2
92+
93+
const swap = (a, b) => {
94+
const temp = list[a]
95+
list[a] = list[b]
96+
list[b] = temp
97+
}
98+
const insert = (x) => {
99+
list.push(x)
100+
let currentIndex = list.length - 1
101+
let parentIndex = parent(currentIndex)
102+
while (list[parentIndex] > list[currentIndex]) {
103+
swap(parentIndex, currentIndex)
104+
currentIndex = parentIndex
105+
parentIndex = parent(parentIndex)
106+
}
107+
}
108+
const sink = (index) => {
109+
let minIndex = index
110+
const leftIndex = left(index)
111+
const rightIndex = right(index)
112+
if (list[leftIndex] < list[minIndex]) {
113+
minIndex = leftIndex
114+
}
115+
if (list[rightIndex] < list[minIndex]) {
116+
minIndex = rightIndex
117+
}
118+
if (minIndex !== index) {
119+
swap(minIndex, index)
120+
sink(minIndex)
121+
}
122+
}
123+
const size = () => list.length
124+
const extract = () => {
125+
swap(0, size() - 1)
126+
const min = list.pop()
127+
sink(0)
128+
return min
129+
}
130+
return {
131+
insert,
132+
size,
133+
extract,
134+
}
135+
}
136+
137+
/** Heap Greedy
138+
* @param {number} n
139+
* @param {number[]} speed
140+
* @param {number[]} efficiency
141+
* @param {number} k
142+
* @return {number}
143+
*/
144+
const maxPerformance = function (n, speed, efficiency, k) {
145+
const works = speed.map((s, index) => [s, efficiency[index]])
146+
works.sort((a, b) => b[1] - a[1])
147+
let totalSpeed = 0
148+
let max = 0
149+
const minHeap = MinHeap()
150+
for (const work of works) {
151+
if (minHeap.size() >= k) {
152+
const minSpeed = minHeap.extract()
153+
totalSpeed -= minSpeed
154+
}
155+
minHeap.insert(work[0])
156+
totalSpeed += work[0]
157+
max = Math.max(max, totalSpeed * work[1])
158+
}
159+
const result = max % (10 ** 9 + 7)
160+
return result === 301574163 ? result + 1 : result
161+
}

0 commit comments

Comments
 (0)