LeetCode 396.

Tags:

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

Code

class Solution {
    public int maxRotateFunction(int[] nums) {
        int prev = 0, sum = 0;
        for (int i=0; i<nums.length; i++) {
            prev += nums[i] * i;
            sum += nums[i];
        }

        int result = Integer.MIN_VALUE;
        for (int i=1; i<=nums.length; i++) {
            prev += (sum - nums[nums.length - i] * nums.length);
            result = Math.max(result, prev);
        }

        return result;
    }
}

Check out the description of this problem at LC 396.