Given an array of integers A
and let n to be its length.
Assume Bk
to be an array obtained by rotating the array A
k positions clock-wise, we define a "rotation function" F
on A
as follow:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]
.
Calculate the maximum value of F(0), F(1), ..., F(n-1)
.
Note:
n is guaranteed to be less than 105.
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
int cur_max = 0;
int sum_ = 0;
int n = A.size();
for (int i = 0; i < n; ++i) {
cur_max += i * A[i];
sum_ += A[i];
}
int result = cur_max;
for (int i = 0; i < n - 1; ++i) {
cur_max += n * A[i] - sum_;
result = max(result, cur_max);
}
return result;
}
};