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;
}
};
本文介绍了一个关于数组旋转的问题,定义了一种特殊的“旋转函数”,并提供了一种高效算法来计算该函数的最大值。该算法利用了数组元素之和以及当前最大值与下一次可能的最大值之间的关系。
1114

被折叠的 条评论
为什么被折叠?



