Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
You are given an array of positive integers nums
. In each operation, you can choose any number nums
from it and reduce it to exactly half. (Note that you can continue to perform operations on the halved number in subsequent operations)
Please return the minimumnums
number of operations that reduce the sum of the array by at least half .
Example 1:
Input: nums = [5,19,8,1] Output: 3 Explanation: The sum of initial nums is 5 + 19 + 8 + 1 = 33. Here's one way to reduce the array sum to at least half: pick the number 19 and reduce it to 9.5. Select the number 9.5 and reduce it to 4.75. Select the number 8 and reduce it to 4. The final array is [5, 4.75, 4, 1], and the sum is 5 + 4.75 + 4 + 1 = 14.75. The sum of nums is reduced by 33 - 14.75 = 18.25, and the reduced part exceeds half of the initial array sum, 18.25 >= 33/2 = 16.5. We need 3 operations to fulfill the title requirement, so return 3. It can be shown that the array sum cannot be reduced by at least half in less than 3 operations.
Example 2:
Input: nums = [3,8,20] Output: 3 Explanation: The sum of initial nums is 3 + 8 + 20 = 31. Here's one way to reduce the sum of an array by at least half: pick the number 20 and reduce it to 10. Select the number 10 and reduce it to 5. Select the number 3 and reduce it to 1.5. The final array is [1.5, 8, 5], and the sum is 1.5 + 8 + 5 = 14.5. The sum of nums is reduced by 31 - 14.5 = 16.5, and the reduced part exceeds half of the initial array sum, 16.5 >= 31/2 = 16.5. We need 3 operations to fulfill the title requirement, so return 3. It can be shown that the array sum cannot be reduced by at least half in less than 3 operations.
hint:
1 <= nums.length <= 105
1 <= nums[i] <= 107
Problem-solving ideas:
* 2208. The minimum number of operations to halve an array sum
* Problem-solving ideas:
* The simplest idea must be to take the maximum value for each sorting, then halve the maximum value, and then add the halved value to the set for sorting and re-take the maximum value.
* So when inserting a collection, if you use the lng method, then the time complexity is n*lng, which is satisfactory.
code:
class Solution2208
{
public:
int halveArray(vector<int> &nums)
{
multiset<double> mySet;
double sum = 0.0;
for (int i = 0; i < nums.size(); i++)
{
sum += nums[i];
mySet.insert(nums[i] * 1.0);
}
int times = 0;
double currentSum = 0;
while (currentSum < sum / 2)
{
auto lastElement = mySet.rbegin();
double value = (*lastElement) / 2.0;
currentSum += value;
mySet.erase(std::prev(lastElement.base()));
mySet.insert(value);
times++;
}
return times;
}
};