题目描述:
396. Rotate Function
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.
Example:
A = [4, 3, 2, 6] F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
解题思路:
刚看到本题最直观的解法就是穷举所有的F值,然而注意到此处n的值可以达到pow(10,5)级别,但是考虑到穷举法的复杂度为n*n,也不是很高,所以就首先尝试了一下,如代码一。
但是由于数据量较大, 所以穷举法超时了。之后又考虑到,即使穷举也没必要将所有的值完全重新算。所谓顺时针的移动可以看作将其中的n-1个值加一,剩余的1个数的系数改为0即可。这种虽然也是穷举但是由于利用了之前的计算结果,所以效率大大提高。(见代码二)
代码展示:
如代码一
//代码一
//穷举法 复杂度 O(n*n)
int maxRotateFunction(vector<int>& A) {
int max_value = INT_MIN;
int n = A.size();
if(n==0)
return 0;
int k=0;
for(int i=0;i<n;i++)
{ k =0;
int tmp =0;
for(int j=0;j<n;j++)
{
if(k+i>=n)
tmp+=A[j]*(k+i-n);
else
tmp+=A[j]*(k+i);
k++;
}
if(tmp>max_value)
{
max_value = tmp;
}
}
return max_value;
}
//代码二
//穷举法 复杂度 O(n)
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
int n = A.size();
if(n==0)
return 0;
long long sum =0;
int max_value = 0;
int ans = 0;
for(int i=0;i<n;i++)
{
sum+=A[i];
max_value+=A[i]*i;
}
ans = max_value;
for(int i=n-1;i>0;i--)
{
ans+=(sum-A[i]*n);
max_value = max(ans,max_value);
}
return max_value;
}
};