-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay36.cpp
More file actions
59 lines (46 loc) · 1.47 KB
/
Day36.cpp
File metadata and controls
59 lines (46 loc) · 1.47 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
This problem was asked by Airbnb.
You are given an array X of floating-point numbers x1, x2, ... xn. These can be rounded up or down to create a corresponding array Y of integers y1, y2, ... yn.
Write an algorithm that finds an appropriate Y array with the following properties:
The rounded sums of both arrays should be equal.
The absolute pairwise difference between elements is minimized. In other words, |x1- y1| + |x2- y2| + ... + |xn- yn| should be as small as possible.
For example, suppose your input is [1.3, 2.3, 4.4]. In this case you cannot do better than [1, 2, 5], which has an absolute difference of |1.3 - 1| + |2.3 - 2| + |4.4 - 5| = 1.
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> roundArray(vector<double> x)
{
vector<int> y;
vector<pair<double, int>> fracParts;
int floorSum = 0;
double totalSum = 0;
int i = 0;
for (double num : x)
{
int n = floor(x[i]);
floorSum += n;
y.push_back(n);
totalSum += num;
fracParts.push_back({num - n, i++});
}
sort(fracParts.begin(), fracParts.end(), greater<>());
int ceils = round(totalSum) - floorSum;
for (int i = 0; i < ceils; i++)
{
int idx = fracParts[i].second;
y[idx] += 1;
}
return y;
}
int main()
{
vector<double> X = {1.3, 2.3, 4.4};
vector<int> Y = roundArray(X);
cout << "Rounded array: ";
for (int y : Y)
{
cout << y << " ";
}
cout << endl;
return 0;
}