zoukankan      html  css  js  c++  java
  • [LeetCode 396.] Rotate Function

    LeetCode 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.

    解题思路

    暴力做法 O(N^2) 是会超时的。注意观察给的例子,发现 F(k) 和 F(k-1) 之间存在相关关系,不用每次重新计算:
    F(k) = F(k-1) + sum(A) - n * A[n - k]
    由此,问题复杂度一下子降到了 O(N)。
    发现递推关系,问题就简单了起来。

    参考代码

    要小心int类型溢出的问题。

    /*
     * @lc app=leetcode id=396 lang=cpp
     *
     * [396] Rotate Function
     */
    
    // @lc code=start
    class Solution {
    public:
    /*
        int maxRotateFunction(vector<int>& A) {
            if (A.empty()) return 0;
    
            int res = INT32_MIN;
            int n = A.size();
            for (int k = 0; k < n; k++) {
                int F = 0;
                for (int i = 0; i < n; i++) {
                    F += ((i + k) % n) * A[i];
                }
                res = max(res, F);
            }
            return res;
        } // TLE, brute force, O(N^2)
    */
        int maxRotateFunction(vector<int>& A) {
            if (A.empty()) return 0;
    
            size_t n = A.size();
            int64_t sum = 0; // avoid overflow
            for (int x : A) {
                sum += x;
            }
            int F0 = 0;
            for (int i = 0; i < n; i++) {
                F0 += i * A[i];
            }
            int res = F0;
            int64_t F = F0; // avoid overflow
            for (int k = 1; k < n; k++) {
                F = F + sum - n * A[n - k];
                res = max(res, (int)F);
            }
            return res;
        }
    };
    // @lc code=end
    
  • 相关阅读:
    我看到的我未曾是你们看到的我。
    nagios状态数据更新不及时问题
    Ubuntu下安装 nagiosgraph报错处理
    禁止、允许PING
    windows批量关机
    [转载]div仿框架(B/S结构软件界面)详解[非quirks模式全兼容]
    rrdtool错误attempt to put segment in horiz list twice
    命令参考大全 iostat
    SAP学习手册
    顾问成长之路
  • 原文地址:https://www.cnblogs.com/zhcpku/p/14480902.html
Copyright © 2011-2022 走看看