Skip to content

Commit ac01e34

Browse files
committed
Weekly Contest 127
1 parent 6cf080b commit ac01e34

4 files changed

+74
-0
lines changed

clumsy-factorial.cc

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Clumsy Factorial
2+
class Solution {
3+
public:
4+
int clumsy(int N) {
5+
if (N <= 2) return N;
6+
int s = N*(N-1)/(N-2);
7+
for (N -= 3; N > 0; N -= 4)
8+
s += N - max(N-1, 0) * max(N-2, 1) / max(N-3, 1);
9+
return s;
10+
}
11+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Construct Binary Search Tree from Preorder Traversal
2+
class Solution {
3+
public:
4+
TreeNode* bstFromPreorder(vector<int>& p) {
5+
vector<TreeNode *> s;
6+
TreeNode *r = nullptr, *y;
7+
for (auto v: p) {
8+
y = 0;
9+
while (s.size() && s.back()->val < v) {
10+
y = s.back();
11+
s.pop_back();
12+
}
13+
s.push_back(new TreeNode(v));
14+
if (!r)
15+
r = s.back();
16+
if (y)
17+
y->right = s.back();
18+
else if (s.size() > 1)
19+
s[s.size()-2]->left = s.back();
20+
}
21+
return r;
22+
}
23+
};
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Maximize Sum Of Array After K Negations
2+
class Solution {
3+
public:
4+
int largestSumAfterKNegations(vector<int>& A, int K) {
5+
auto it = partition(A.begin(), A.end(), bind(less<>(), placeholders::_1, 0));
6+
if (K < it-A.begin()) {
7+
nth_element(A.begin(), A.begin()+K, it);
8+
transform(A.begin(), A.begin()+K, A.begin(), negate<>());
9+
} else {
10+
transform(A.begin(), it, A.begin(), negate<>());
11+
if (K-(it-A.begin()) & 1) {
12+
it = min_element(A.begin(), it);
13+
auto it1 = min_element(it, A.end());
14+
(it == A.begin() || it1 != A.end() && *it1 < *it ? *it1 : *it) *= -1;
15+
}
16+
}
17+
return accumulate(A.begin(), A.end(), 0);
18+
}
19+
};
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Minimum Domino Rotations For Equal Row
2+
class Solution {
3+
public:
4+
int minDominoRotations(vector<int>& A, vector<int>& B) {
5+
int r = A.size()+1;
6+
for (int d = 1; d <= 6; d++) {
7+
int a = 0, b = 0;
8+
for (int i = 0; i < A.size(); i++) {
9+
if (d == A[i]) {
10+
if (d != B[i])
11+
b++;
12+
} else if (d == B[i])
13+
a++;
14+
else
15+
a = b = A.size()+1;
16+
}
17+
r = min(r, min(a, b));
18+
}
19+
return r > n ? -1 : r;
20+
}
21+
};

0 commit comments

Comments
 (0)