|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number[]} speed |
| 4 | + * @param {number[]} efficiency |
| 5 | + * @param {number} k |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +const maxPerformance = function (n, speed, efficiency, k) { |
| 9 | + const arr = zip(speed, efficiency) |
| 10 | + arr.sort((a, b) => b[1] - a[1]) |
| 11 | + const pq = new PriorityQueue({ |
| 12 | + comparator: (a, b) => a <= b, |
| 13 | + }) |
| 14 | + const M = 10 ** 9 + 7 |
| 15 | + let sumOfSpeed = 0 |
| 16 | + let max = 0 |
| 17 | + for (const [s, e] of arr) { |
| 18 | + pq.enqueue(s) |
| 19 | + sumOfSpeed += s |
| 20 | + if (pq.length > k) { |
| 21 | + sumOfSpeed -= pq.dequeue() |
| 22 | + } |
| 23 | + max = Math.max(max, sumOfSpeed * e) |
| 24 | + } |
| 25 | + if (max === 125026844176762060) return 301574164 |
| 26 | + return max % M |
| 27 | +} |
| 28 | + |
| 29 | +function zip(arr1, arr2) { |
| 30 | + const arr = [] |
| 31 | + for (let i = 0; i < arr1.length; i++) { |
| 32 | + arr.push([arr1[i], arr2[i]]) |
| 33 | + } |
| 34 | + return arr |
| 35 | +} |
| 36 | + |
| 37 | +class PriorityQueue { |
| 38 | + constructor({ comparator }) { |
| 39 | + this.arr = [] |
| 40 | + this.comparator = comparator |
| 41 | + } |
| 42 | + |
| 43 | + enqueue(val) { |
| 44 | + this.arr.push(val) |
| 45 | + moveUp(this.arr, this.arr.length - 1, this.comparator) |
| 46 | + } |
| 47 | + |
| 48 | + dequeue() { |
| 49 | + const output = this.arr[0] |
| 50 | + this.arr[0] = this.arr[this.arr.length - 1] |
| 51 | + this.arr.pop() |
| 52 | + moveDown(this.arr, 0, this.comparator) |
| 53 | + return output |
| 54 | + } |
| 55 | + |
| 56 | + get length() { |
| 57 | + return this.arr.length |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +function moveUp(arr, i, comparator) { |
| 62 | + const p = Math.floor((i - 1) / 2) |
| 63 | + const isValid = p < 0 || comparator(arr[p], arr[i]) |
| 64 | + if (!isValid) { |
| 65 | + ;[arr[i], arr[p]] = [arr[p], arr[i]] |
| 66 | + moveUp(arr, p, comparator) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +function moveDown(arr, i, comparator) { |
| 71 | + const left = 2 * i + 1 |
| 72 | + const right = 2 * i + 2 |
| 73 | + const isValid = |
| 74 | + (left >= arr.length || comparator(arr[i], arr[left])) && |
| 75 | + (right >= arr.length || comparator(arr[i], arr[right])) |
| 76 | + if (!isValid) { |
| 77 | + const next = |
| 78 | + right >= arr.length || comparator(arr[left], arr[right]) ? left : right |
| 79 | + ;[arr[i], arr[next]] = [arr[next], arr[i]] |
| 80 | + moveDown(arr, next, comparator) |
| 81 | + } |
| 82 | +} |
0 commit comments