Skip to content

Commit 63b39e2

Browse files
authored
Create find-missing-observations.cpp
1 parent 4b07d96 commit 63b39e2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

C++/find-missing-observations.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
7+
static const int MAX_V = 6;
8+
static const int MIN_V = 1;
9+
10+
const int total = accumulate(cbegin(rolls), cend(rolls), 0);
11+
const int missing = mean * (n + size(rolls)) - total;
12+
if (missing < MIN_V * n || missing > MAX_V * n) {
13+
return {};
14+
}
15+
const int q = missing / n;
16+
const int r = missing % n;
17+
vector<int> result(n);
18+
for (int i = 0; i < size(result); ++i) {
19+
result[i] = q + int(i < r);
20+
}
21+
return result;
22+
}
23+
};
24+
25+
26+
// Time: O(n)
27+
// Space: O(1)
28+
class Solution2 {
29+
public:
30+
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
31+
static const int MAX_V = 6;
32+
static const int MIN_V = 1;
33+
34+
const int total = accumulate(cbegin(rolls), cend(rolls), 0);
35+
const int missing = mean * (n + size(rolls)) - total;
36+
if (missing < MIN_V * n || missing > MAX_V * n) {
37+
return {};
38+
}
39+
const int q = (missing - MIN_V * n) / (MAX_V - MIN_V);
40+
const int r = (missing - MIN_V * n) % (MAX_V - MIN_V);
41+
vector<int> result(n);
42+
for (int i = 0; i < size(result); ++i) {
43+
result[i] = (i < q) ? MAX_V : ((i == q) ? MIN_V + r : MIN_V);
44+
}
45+
return result;
46+
}
47+
};

0 commit comments

Comments
 (0)