Skip to content

Commit 38da512

Browse files
authored
Create make-k-subarray-sums-equal.cpp
1 parent e86d188 commit 38da512

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/make-k-subarray-sums-equal.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// math, greedy
5+
class Solution {
6+
public:
7+
long long makeSubKSumEqual(vector<int>& arr, int k) {
8+
const int l = gcd(k, size(arr));
9+
int64_t result = 0;
10+
for (int i = 0; i < l; ++i) {
11+
vector<int> vals;
12+
for (int j = i; j < size(arr); j += l) {
13+
vals.emplace_back(arr[j]);
14+
}
15+
nth_element(begin(vals), begin(vals) + size(vals) / 2, end(vals));
16+
result += accumulate(cbegin(vals), cend(vals), 0LL,
17+
[&](const auto& total, const auto& x) {
18+
return total + abs(x - vals[size(vals) / 2]);
19+
});
20+
}
21+
return result;
22+
}
23+
};

0 commit comments

Comments
 (0)