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.

这题是leetcode第四次周赛第一题,难度easy,所以我上来就直接用暴力循环做了,也就是枚举所有的计算结果,复杂度是O(n^2)。结果超时了,看来比赛的时候不能为了图方便就抱有侥幸心理啊。

方法一:O(n^2)基本枚举
int maxRotateFunction(vector<int>& A) {
    int maxval = INT_MIN;
    int len = A.size();
    if (len == 0) return 0;
    for (int j = 0; j < len; j++) {
        int temp = 0;
        int st = j;
        for (int i = 0; i < len; i++) {
            temp += ((st++) % len) * A[i];
        }
        maxval = max(temp, maxval);
    }
    return maxval;
}
方法二:O(n)递推公式

其实跟第一个一样,也是要枚举所有的和,只不过每一个的计算不需要重新检索一遍数组,当我们计算出F(0)之后,F(1)可以直接推导出来,之后的也可以以此类推,所以每一个和的计算变成了常数时间,所以总的时间复杂度就降为O(n)。
递推公式为:

F(i) = F(i-1) + sum(A) - A[n-i] - (n-1)*A[n-i]

这个公式很好理解,大家把前后两组求和的系数写出来,对比下会发现,后者跟前者多了sum(A) - A[n-i] ,少了(n-1)*A[n-i]。
代码如下:

int maxRotateFunction(vector<int>& A) {
    int i, res = 0;
    int n = A.size();
    if (n == 0 || n == 1) return res;
    int f0 = 0, sum = 0;
    for (i = 0; i < n; i++) {
        f0 += i * A[i];
        sum += A[i];
    }
    res = f0;
    for (i = 1; i < n; i++) {
        f0 = f0 + sum - A[n-i] - (n-1)*A[n-i];
        res = max(res, f0);
    }
    return res;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值