|
1 | 1 | class Solution { |
2 | 2 | public: |
3 | | - int minCostToEqualizeArray(std::vector<int> &A, int c1, int c2) { |
4 | | - int ma = *std::max_element(A.begin(), A.end()); |
5 | | - int mi = *std::min_element(A.begin(), A.end()); |
6 | | - int n = A.size(), mod = 1000000007; |
7 | | - long long su = std::accumulate(A.begin(), A.end(), 0LL); |
| 3 | + int minCostToEqualizeArray(std::vector<int>& A, int c1, int c2) { |
| 4 | + const int mod = 1'000'000'007; |
| 5 | + const int n = static_cast<int>(A.size()); |
| 6 | + const int ma = *std::max_element(A.begin(), A.end()); |
| 7 | + const int mi = *std::min_element(A.begin(), A.end()); |
| 8 | + const long long su = std::accumulate(A.begin(), A.end(), 0LL); |
| 9 | + |
8 | 10 | long long total = 1LL * ma * n - su; |
9 | 11 |
|
10 | 12 | if (c1 * 2 <= c2 || n <= 2) { |
11 | | - return (total * c1) % mod; |
| 13 | + return static_cast<int>(total * c1 % mod); |
12 | 14 | } |
13 | 15 |
|
14 | 16 | long long op1 = std::max(0LL, (ma - mi) * 2 - total); |
15 | 17 | long long op2 = total - op1; |
16 | 18 | long long res = (op1 + op2 % 2) * c1 + op2 / 2 * c2; |
17 | 19 |
|
18 | 20 | total += op1 / (n - 2) * n; |
19 | | - op1 %= n - 2; |
20 | | - op2 = total - op1; |
21 | | - res = std::min(res, (op1 + op2 % 2) * c1 + op2 / 2 * c2); |
| 21 | + op1 %= (n - 2); |
| 22 | + op2 = total - op1; |
| 23 | + res = std::min(res, (op1 + op2 % 2) * c1 + op2 / 2 * c2); |
22 | 24 |
|
23 | | - for (int i = 0; i < 2; i++) { |
| 25 | + for (int i = 0; i < 2; ++i) { |
24 | 26 | total += n; |
25 | 27 | res = std::min(res, total % 2 * c1 + total / 2 * c2); |
26 | 28 | } |
27 | | - |
28 | | - return res % mod; |
| 29 | + return static_cast<int>(res % mod); |
29 | 30 | } |
30 | 31 | }; |
0 commit comments