Leetcode

Rotate Function

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  int maxRotateFunction(vector<int>& nums) {
    const int sum = accumulate(begin(nums), end(nums), 0);
    int f = 0;

    // calculate F(0) first
    for (int i = 0; i < nums.size(); ++i)
      f += i * nums[i];

    int ans = f;

    for (int i = nums.size() - 1; i > 0; --i) {
      f += sum - nums.size() * nums[i];
      ans = max(ans, f);
    }

    return ans;
  }
};

JAVA

class Solution {
  public int maxRotateFunction(int[] nums) {
    final int sum = Arrays.stream(nums).sum();
    int f = 0;

    // calculate F(0) first
    for (int i = 0; i < nums.length; ++i)
      f += i * nums[i];

    int ans = f;

    for (int i = nums.length - 1; i >= 0; --i) {
      f += sum - nums.length * nums[i];
      ans = Math.max(ans, f);
    }

    return ans;
  }
}

Python

class Solution:
  def maxRotateFunction(self, nums: List[int]) -> int:
    f = sum(i * num for i, num in enumerate(nums))
    ans = f
    summ = sum(nums)

    for a in reversed(nums):
      f += summ - len(nums) * a
      ans = max(ans, f)

    return ans