Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

396. Rotate Function - Leetcode Solution

Code Implementation

class Solution:
    def maxRotateFunction(self, nums):
        n = len(nums)
        total_sum = sum(nums)
        F = sum(i * num for i, num in enumerate(nums))
        max_value = F
        for k in range(1, n):
            F = F + total_sum - n * nums[-k]
            max_value = max(max_value, F)
        return max_value
      
class Solution {
public:
    int maxRotateFunction(vector<int>& nums) {
        int n = nums.size();
        long total_sum = 0, F = 0;
        for (int i = 0; i < n; ++i) {
            total_sum += nums[i];
            F += i * nums[i];
        }
        long max_value = F;
        for (int k = 1; k < n; ++k) {
            F = F + total_sum - n * nums[n - k];
            if (F > max_value) max_value = F;
        }
        return (int)max_value;
    }
};
      
class Solution {
    public int maxRotateFunction(int[] nums) {
        int n = nums.length;
        long totalSum = 0, F = 0;
        for (int i = 0; i < n; i++) {
            totalSum += nums[i];
            F += (long)i * nums[i];
        }
        long maxValue = F;
        for (int k = 1; k < n; k++) {
            F = F + totalSum - (long)n * nums[n - k];
            if (F > maxValue) maxValue = F;
        }
        return (int)maxValue;
    }
}
      
var maxRotateFunction = function(nums) {
    const n = nums.length;
    let totalSum = nums.reduce((a, b) => a + b, 0);
    let F = nums.reduce((acc, num, i) => acc + i * num, 0);
    let maxValue = F;
    for (let k = 1; k < n; k++) {
        F = F + totalSum - n * nums[n - k];
        if (F > maxValue) maxValue = F;
    }
    return maxValue;
};
      

Problem Description

The Rotate Function problem asks you to compute, for a given array nums of length n, the maximum value of a function F(k) defined as follows:

For each integer k from 0 to n-1, rotate nums by k positions (so the array shifts right, wrapping elements), and compute:

F(k) = 0 * arr_k[0] + 1 * arr_k[1] + ... + (n-1) * arr_k[n-1]
where arr_k is the array after rotating nums by k positions.

Your task is to return the maximum value among all F(k) for k from 0 to n-1.

  • Each element in nums can be any integer.
  • There is exactly one valid solution.
  • You must not reuse or skip elements; each rotation uses the same elements in a different order.

Thought Process

At first glance, the problem seems to require recalculating the rotation function for every possible rotation of the array. That is, for each k, you would rotate the array and then compute the sum as described. This brute-force approach, however, quickly becomes inefficient for large arrays because each rotation takes O(n) time, and there are n possible rotations, resulting in O(n2) time complexity.

The key insight is to look for a relationship between F(k) and F(k-1) that avoids recalculating everything from scratch. If we can update the function value in constant time as we move from one rotation to the next, we can reduce the time complexity significantly.

By analyzing how the indices and values change with each rotation, we can derive a mathematical formula to compute F(k) from F(k-1). This shift from brute-force to an optimized approach is crucial for solving the problem efficiently.

Solution Approach

  • Step 1: Compute Initial Values
    • Calculate the sum of all elements in nums (call it total_sum).
    • Compute F(0), which is the rotate function without any rotation.
  • Step 2: Derive the Relationship
    • Notice that when you rotate the array by one position, each element's index increases by one (except the last element, which moves to the front and its index becomes 0).
    • You can derive that:
      F(k) = F(k-1) + total_sum - n * nums[n - k]
    • Here, nums[n - k] is the element that moves from the end to the start in the k-th rotation.
  • Step 3: Iterate and Update
    • Use the above formula to compute each F(k) in O(1) time for all k from 1 to n-1.
    • Track the maximum value encountered during the iteration.
  • Step 4: Return the Result
    • After processing all possible rotations, return the maximum value found.

This approach leverages the relationship between consecutive rotations and avoids unnecessary recomputation, resulting in a highly efficient solution.

Example Walkthrough

Let's walk through an example with nums = [4, 3, 2, 6].

  • Step 1: Calculate total_sum and F(0)
    total_sum = 4 + 3 + 2 + 6 = 15
    F(0) = 0*4 + 1*3 + 2*2 + 3*6 = 0 + 3 + 4 + 18 = 25
  • Step 2: Use the formula to compute F(1)
    F(1) = F(0) + total_sum - n * nums[n-1]
    F(1) = 25 + 15 - 4*6 = 25 + 15 - 24 = 16
  • Step 3: Compute F(2)
    F(2) = F(1) + total_sum - n * nums[n-2]
    F(2) = 16 + 15 - 4*2 = 16 + 15 - 8 = 23
  • Step 4: Compute F(3)
    F(3) = F(2) + total_sum - n * nums[n-3]
    F(3) = 23 + 15 - 4*3 = 23 + 15 - 12 = 26
  • Maximum value: Among 25, 16, 23, 26, the maximum is 26.

This step-by-step calculation demonstrates how each new value builds on the previous one, making the process efficient and easy to follow.

Time and Space Complexity

  • Brute-force Approach:
    • For each of the n rotations, you recalculate the sum from scratch, leading to O(n2) time complexity.
    • Space complexity is O(n) due to storing the rotated arrays.
  • Optimized Approach:
    • We compute the initial values in O(n) time, and each subsequent F(k) in O(1) time, for a total of O(n) time complexity.
    • We use only a few integer variables for tracking sums and maximums, so the space complexity is O(1).

The optimized approach is highly efficient and suitable for large input sizes.

Summary

The Rotate Function problem is a classic example of transforming a seemingly expensive brute-force problem into an efficient linear-time solution by recognizing patterns and mathematical relationships. By relating the function value of each rotation to the previous one, we avoid redundant calculations and achieve O(n) time complexity. The key insight is the formula linking F(k) and F(k-1), which allows us to traverse all rotations with minimal work. This approach is both elegant and practical for real-world use.