[LeetCode] Minimum Operations to Halve Array Sum

2208. Minimum Operations to Halve Array Sum

You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)

Return the minimum number of operations to reduce the sum of nums by at least half.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int halveArray(vector<int>& nums) {
int op = 0;
long double sum = 0;
priority_queue<double> pq;
for(int i = 0; i < nums.size(); i++) {
pq.push(nums[i]);
sum += nums[i];
}
long double target = sum;
while(target * 2 > sum) {
double tp = pq.top(); pq.pop();
target -= tp/2;
pq.push(tp/2);
op++;
}
return op;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/minimum-operations-to-halve-array-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.