๐๋งํฌ
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/description/
๐จํ์ด
์ด ๋ฌธ์ ์ ์กฐ๊ฑด์ ๋ณด๋ฉด ๋จ์ํ ์ ๋ ฌ์ ์ด์ฉํด์ ํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ ๊ฒ์ด๋ผ๊ณ ์๊ฐ๋์ด ์ฐ์ ์์ ํ๋ฅผ ์ด์ฉํ์ฌ ์ฐ์ฐํ์๋ฅผ ์ต์ ํ ํ์๋ค. ์ฐ์ ์์ ํ๋ฅผ ๊ตฌํํ๊ธฐ ์ํด ํ(์์ ์ด์ง ํธ๋ฆฌ) ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ด์ฉํ์๊ณ ์ฐ์ ์์ ํ์์ ๊ฐ์ฅ ํฐ ๊ฐ์ ๋ฐ์ผ๋ก ๋๋๋ฉด์ ๊ณ์ฐํ์๋ฅผ ์นด์ดํ ํ์ฌ ๋ฌธ์ ๋ฅผ ํ ์ ์์๋ค. ํด๋น ๋ฌธ์ ์ ์๊ฐ๋ณต์ก๋๋ O( n log n ) ์ด๋ค. ( ์๊ฐ๋ณต์ก๋ ๊ด๋ก๋๋ก log์ ๋ฐ์ ์๋ต )
/**
* @param {number[]} nums
* @return {number}
*/
var halveArray = function (nums) {
class MaxHeap {
constructor() {
this.heap = [];
}
_swap(i, j) {
let temp = this.heap[i];
this.heap[i] = this.heap[j];
this.heap[j] = temp;
}
push(n) {
let heap = this.heap;
heap.push(n);
if (heap.length >= 2) {
let childIdx = heap.length - 1;
let parentIdx = parseInt((childIdx - 1) / 2);
while (heap[parentIdx] < heap[childIdx]) {
this._swap(parentIdx, childIdx);
childIdx = parentIdx;
parentIdx = parseInt((childIdx - 1) / 2);
if (childIdx === 0) break;
}
}
}
pop() {
let q = this.heap;
const max = q[0];
q[0] = q.pop();
if (q.length >= 2) {
let parentIdx = 0;
let [leftChildIdx, rightChildIdx] = [parentIdx * 2 + 1, parentIdx * 2 + 2];
while ((q[leftChildIdx] && q[leftChildIdx] > q[parentIdx]) || (q[rightChildIdx] && q[rightChildIdx] > q[parentIdx])) {
let maxChildIdx = leftChildIdx;
if (q[rightChildIdx] && q[rightChildIdx] > q[leftChildIdx]) {
maxChildIdx = rightChildIdx;
}
this._swap(parentIdx, maxChildIdx);
parentIdx = maxChildIdx;
leftChildIdx = parentIdx * 2 + 1;
rightChildIdx = parentIdx * 2 + 2;
}
}
return max;
}
}
let sum = nums.reduce((acc, cur) => {
return acc + cur;
}, 0);
let half = sum / 2;
let totalMinus = 0;
const maxPriorityQueue = new MaxHeap();
let cnt = 0;
nums.forEach((n) => {
maxPriorityQueue.push(n);
});
while (half > totalMinus) {
let half = maxPriorityQueue.pop() / 2;
totalMinus += half;
maxPriorityQueue.push(half);
++cnt;
}
return cnt;
};
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode [JS] > 859. Buddy strings (0) | 2025.04.05 |
---|---|
LeetCode [JS] > 2780. Minimum Index of a Valid Split (0) | 2025.04.05 |
LeetCode > 1346. Check If N and Its Double Exist (0) | 2025.04.03 |
LeetCode > 806. Number of Lines To Write String (0) | 2025.04.02 |
LeetCode > 2022. Convert 1D Array Into 2D Array (0) | 2025.03.29 |