396. Rotate Function

Problem:

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 * B_k[0] + 1 * B_k[1] + ... + (n-1) * B_k[n-1]\).

Calculate the maximum value of F(0), F(1), ..., F(n-1).

Note:
n is guaranteed to be less than \(10^5\).

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.

思路

Solution (C++):

int maxRotateFunction(vector<int>& A) {
    if (A.empty())  return 0;
    int n = A.size();
    long long F = 0, sum = 0;
    for (int i= 0; i < n; ++i) {
        F += i * A[i];
        sum += A[i];
    }
    long long max_rot = F;
    for (int i = n-1; i >= 0; --i) {
        F = F + sum - (long long)n * (long long)A[i];
        max_rot = max(max_rot, F);
    }
    return max_rot;
}

性能

Runtime: 8 ms  Memory Usage: 7.5 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

原文链接: https://www.cnblogs.com/dysjtu1995/p/12675548.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    396. Rotate Function

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/341180

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:57
下一篇 2023年3月2日 上午12:58

相关推荐