LeetCode刷题实战396:旋转函数
共 2755字,需浏览 6分钟
·
2021-10-01 23:50
You are given an integer array nums of length n.
Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Return the maximum value of F(0), F(1), ..., F(n-1).
The test cases are generated so that the answer fits in a 32-bit integer.
示例
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
所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
解题
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
long sum_A=0;//数组A的元素和
long sum_Ak=0;//在k=0,既不旋转是获得结果和
long n=A.size();//数组A的元素个数
for(int i=0;i<n;++i){//计算
sum_A+=A[i];
sum_Ak+=A[i]*i;
}
long max_sumk=sum_Ak;//初始化,最大的值
for(int i=1;i<n;++i){
sum_Ak=sum_A+sum_Ak-n*A[n-i];//使用之前的值,求出当前的值
max_sumk=max_sumk<sum_Ak?sum_Ak:max_sumk;//更新可能的更大的值
}
return max_sumk;//发那会结果
}
};
LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素