Skip to content

Commit

Permalink
feat(C++): Add 2208
Browse files Browse the repository at this point in the history
  • Loading branch information
euchangxian committed Oct 14, 2024
1 parent d27ae88 commit c6d59f9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
36 changes: 36 additions & 0 deletions C++/2208-MinimumOperationsToHalveArraySum/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <algorithm>
#include <cstddef>
#include <vector>

using namespace std;
class Solution {
public:
int halveArray(vector<int>& nums) {
const size_t n = nums.size();

double sum = 0;
vector<double> dblNums(n);
for (size_t i = 0; i < n; ++i) {
dblNums[i] = static_cast<double>(nums[i]);
sum += dblNums[i];
}
// Avoid casting. Ceiling Division.
double target = sum / 2;

std::make_heap(dblNums.begin(), dblNums.end());

int operations = 0;
// Greedily pick the largest num and halve it.
while (target > 0) {
const double halved = dblNums.front() / 2;
std::pop_heap(dblNums.begin(), dblNums.end());

target -= halved;

dblNums.back() = halved;
std::push_heap(dblNums.begin(), dblNums.end());
++operations;
}
return operations;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ Now solving in C++. Like it.
| 2181 | MergeNodesInBetweenZeros | [![C++](assets/c++.svg)](C++/2181-MergeNodesInBetweenZeros/Solution.cpp) |
| 2191 | SortTheJumbledNumbers | [![C++](assets/c++.svg)](C++/2191-SortTheJumbledNumbers/Solution.cpp) |
| 2196 | CreateBinaryTreeFromDescriptions | [![C++](assets/c++.svg)](C++/2196-CreateBinaryTreeFromDescriptions/Solution.cpp) |
| 2208 | MinimumOperationsToHalveArraySum | [![C++](assets/c++.svg)](C++/2208-MinimumOperationsToHalveArraySum/Solution.cpp) |
| 2220 | MinimumBitFlipsToConvertNumber | [![C++](assets/c++.svg)](C++/2220-MinimumBitFlipsToConvertNumber/Solution.cpp) |
| 2246 | LongestPathWithDifferentAdjacentCharacters | [![C++](assets/c++.svg)](C++/2246-LongestPathWithDifferentAdjacentCharacters/Solution.cpp) |
| 2275 | LargestCombinationWithBitwiseANDGreaterThanZero | [![C++](assets/c++.svg)](C++/2275-LargestCombinationWithBitwiseANDGreaterThanZero/Solution.cpp) |
Expand Down

0 comments on commit c6d59f9

Please sign in to comment.