• 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

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    github pages 正确访问方式
    jetty 热部署
    mysql 距离函数
    通过微信公众号ID生成公众号的二维码
    SQL Server 数据库备份失败解决方法
    js 替换部分内容为星号
    mysql 允许远程登录
    nginx 跨域配置
    两台阿里云服务器之间数据迁移
    新装修入住常识有什么
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12675548.html
Copyright © 2020-2023  润新知