forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimize-rounding-error-to-meet-target.cpp
More file actions
34 lines (32 loc) · 1.01 KB
/
minimize-rounding-error-to-meet-target.cpp
File metadata and controls
34 lines (32 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Time: O(n) on average
// Space: O(n)
class Solution {
public:
string minimizeError(vector<string>& prices, int target) {
vector<double> errors;
int lower = 0, upper = 0;
for (const auto& price : prices) {
const auto& p = stod(price);
lower += floor(p);
upper += ceil(p);
if (p != floor(p)) {
errors.emplace_back(p - floor(p));
}
}
if (target < lower || target > upper) {
return "-1";
}
int lower_round_count = upper - target;
nth_element(errors.begin(), errors.begin() + lower_round_count, errors.end());
double min_error = 0.0;
for (int i = 0; i < errors.size(); ++i) {
if (i < lower_round_count) {
min_error += errors[i];
} else {
min_error += 1.0 - errors[i];
}
}
const auto& result = to_string(min_error);
return result.substr(0, result.find(".") + 4);
}
};