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 _theminimum number of operations to reduce the sum of _numsbyat least half.
Input: nums =[5,19,8,1]Output: 3Explanation: The initial sum of nums is equal to 5+19+8+1=33.The following is one of the ways to reduce the sum by at least half:Pick the number 19 and reduce it to 9.5.Pick the number 9.5 and reduce it to 4.75.Pick the number 8 and reduce it to 4.The final array is[5,4.75,4,1]with a total sum of 5+4.75+4+1=14.75.The sum of nums has been reduced by 33-14.75=18.25, which is at least half of the initial sum,18.25>=33/2=16.5.Overall,3 operations were used so we return3.It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Input: nums =[3,8,20]Output: 3Explanation: The initial sum of nums is equal to 3+8+20=31.The following is one of the ways to reduce the sum by at least half:Pick the number 20 and reduce it to 10.Pick the number 10 and reduce it to 5.Pick the number 3 and reduce it to 1.5.The final array is[1.5,8,5]with a total sum of 1.5+8+5=14.5.The sum of nums has been reduced by 31-14.5=16.5, which is at least half of the initial sum,16.5>=31/2=15.5.Overall,3 operations were used so we return3.It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
To reduce the sum by at least half in minimum steps, always halve the largest number available. This greedy approach ensures the biggest reduction per operation.
import java.util.PriorityQueue
classSolution {
funhalveArray(nums: IntArray): Int {
val pq = PriorityQueue<Double>(compareByDescending { it })
var sum = 0.0for (v in nums) {
sum += v
pq.add(v.toDouble())
}
val target = sum / 2var ans = 0while (sum > target) {
val x = pq.poll()
sum -= x / 2 pq.add(x / 2)
ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import heapq
classSolution:
defhalveArray(self, nums: list[int]) -> int:
h = [-float(x) for x in nums]
heapq.heapify(h)
total: float = sum(nums)
target: float = total /2 ans: int =0 curr: float = total
while curr > target:
x: float =-heapq.heappop(h)
curr -= x /2 heapq.heappush(h, -x /2)
ans +=1return ans
use std::collections::BinaryHeap;
impl Solution {
pubfnhalve_array(nums: Vec<i32>) -> i32 {
letmut pq = BinaryHeap::new();
letmut sum =0.0;
for v in nums {
sum += v asf64;
pq.push(v asf64);
}
let target = sum /2.0;
letmut ans =0;
while sum > target {
let x = pq.pop().unwrap();
sum -= x /2.0;
pq.push(x /2.0);
ans +=1;
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
halveArray(nums: number[]):number {
consth: number[] = [...nums].map(x=>-x);
h.sort((a, b) =>a-b);
lettotal=nums.reduce((a, b) =>a+b, 0);
lettarget=total/2;
letans=0;
letcurr=total;
while (curr>target) {
h.sort((a, b) =>a-b);
constx=-h.shift()!;
curr-=x/2;
h.push(-(x/2));
ans++;
}
returnans;
}
}