Skip to content

Commit 631b267

Browse files
authored
Create minimum-cost-to-equalize-array.cpp
1 parent 8e48f00 commit 631b267

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// constructive algorithms, math
5+
class Solution {
6+
public:
7+
int minCostToEqualizeArray(vector<int>& nums, int cost1, int cost2) {
8+
static const int MOD = 1e9 + 7;
9+
10+
const int n = size(nums);
11+
const int64_t mx = ranges::max(nums);
12+
int64_t total = mx * n - accumulate(cbegin(nums), cend(nums), 0ll);
13+
// fill until mx with only cost1 operations
14+
if (n <= 2 || 2 * cost1 <= cost2) {
15+
return total * cost1 % MOD;
16+
}
17+
18+
int64_t result = numeric_limits<int64_t>::max();
19+
// fill until mx with more cost2 operations and fewer cost1 operations
20+
const int64_t mn = ranges::min(nums);
21+
int64_t cnt1 = max((mx - mn) - (total - (mx - mn)), static_cast<int64_t>(0));
22+
int64_t cnt2 = total - cnt1;
23+
result = min(result, (cnt1 + cnt2 % 2) * cost1 + cnt2 / 2 * cost2);
24+
25+
// fill until mx+x with most cost2 operations and fewest cost1 operations,
26+
// where x is the max of x s.t. cnt1+x >= (n-1)*x => cnt1 >= (n-2)*x
27+
const int64_t x = cnt1 / (n - 2);
28+
cnt1 %= n - 2;
29+
total += n * x;
30+
cnt2 = total - cnt1;
31+
result = min(result, (cnt1 + cnt2 % 2) * cost1 + (cnt2 / 2) * cost2);
32+
33+
// fill until mx+x+1 or mx+x+2 with nearly all cost2 operations and at most one cost1 operation
34+
for (int _ = 0; _ < 2; ++_) { // increase twice is for odd n
35+
total += n;
36+
result = min(result, total % 2 * cost1 + total / 2 * cost2);
37+
}
38+
return result % MOD;
39+
}
40+
};

0 commit comments

Comments
 (0)