Approach
Sorting and greedy selection
For Minimize Rounding Error to Meet Target, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 38 lines of C++ from the credited upstream file 1058.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string minimizeError(vector<string>& prices, int target) {4 5 6 vector<tuple<double, double, double>> A;7 int sumFloored = 0;8 int sumCeiled = 0;9 10 for (const string& p : prices) {11 const double price = stod(p);12 const int floored = floor(price);13 const int ceiled = ceil(price);14 sumFloored += floored;15 sumCeiled += ceiled;16 const double costFloor = price - static_cast<double>(floored);17 const double costCeil = static_cast<double>(ceiled) - price;18 A.emplace_back(costCeil - costFloor, costCeil, costFloor);19 }20 21 if (sumFloored > target || sumCeiled < target)22 return "-1";23 24 ranges::sort(A);25 26 double sumError = 0.0;27 const int nCeiled = target - sumFloored;28 for (int i = 0; i < nCeiled; ++i)29 sumError += get<1>(A[i]);30 for (int i = nCeiled; i < A.size(); ++i)31 sumError += get<2>(A[i]);32 33 stringstream ss;34 ss << std::fixed << std::setprecision(3) << sumError;35 return ss.str();36 }37};38