LeetCode 396: Rotate Function
You are given an integer array nums of length n.
Assume F(k) is a function that calculates the sum of the products of each element in nums with their respective indexes after nums is rotated k times.
The rotation is done in such a manner that:
k = 1, the last element moves to the first position, and all other elements are shifted to the right.k = n-1, the same rightward shift continues.Define F(k) as:
F(k) = 0 * nums[k] + 1 * nums[k+1] + ... + (n-1) * nums[k-1]
The task is to find out the maximum value after calculating F(k) for all k in the range [0, n-1].
n?nums array?F(k)?F(k) for all rotations k from 0 to n-1.F(k) would involve a lot of repeated calculations, so we need an optimal approach.F(k) to F(k+1) can be derived using the relationship between consecutive rotations rather than recalculating from scratch each time.F(0) as the initial state:
F(0) = 0 * nums[0] + 1 * nums[1] + ... + (n-1) * nums[n-1]
F(k+1), the value can be derived from F(k):
F(k+1) = F(k) + sum(nums) - n * nums[n-k]
sum(nums) is the sum of all elements in nums.sum(nums) and F(0) initially.1 to n-1 and use the relationship to compute F(k+1) from F(k).public class RotateFunction {
public int maxRotateFunction(int[] nums) {
int n = nums.length;
if (n == 0) return 0;
int sum = 0;
int f = 0;
// Compute sum of all numbers and the initial F(0)
for (int i = 0; i < n; i++) {
sum += nums[i];
f += i * nums[i];
}
int max = f;
// Compute F(k) iteratively and update the maximum found
for (int i = 1; i < n; i++) {
f = f + sum - n * nums[n - i];
max = Math.max(max, f);
}
return max;
}
public static void main(String[]args) {
RotateFunction rf = new RotateFunction();
int[] nums = {4, 3, 2, 6};
System.out.println(rf.maxRotateFunction(nums)); // Output: 26
}
}
F(k), which does not depend on the input size n.This solution efficiently computes the desired maximum value of the rotate function by leveraging the mathematical relationship between consecutive rotations, avoiding redundant calculations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?