You are given an integer array nums of length n.
Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Return the maximum value of F(0), F(1), ..., F(n-1).
The test cases are generated so that the answer fits in a 32-bit integer.
Train of thought
- Rotate the position of elements in an array and calculate the sum of all each element multiply index, find the max sum
Solution
public static int maxRotateFunction(int[] nums) {
int maxRotate = Integer.MIN_VALUE;
int rotateCount = 0;
while (rotateCount < nums.length) {
// rotate the element of an array
int temp = nums[0];
for (int i = 0; i < nums.length - 1; i++) {
nums[i] = nums[i + 1];
}
nums[nums.length - 1] = temp;
int rotate = 0;
// calculate sum
for (int i = 0; i < nums.length; i++) {
rotate += i * nums[i];
}
maxRotate = Math.max(rotate, maxRotate);
rotateCount++;
}
return maxRotate;
}
The complexity
Time complexity: O(n²)
Space complexity: O(1)
Trouble
Time Limit Exceeded (TLE) issue raises.
How to solve it?
Train of thought after optimization
Evolve into a mathematical problem according to the law.
Let the array elements be: array = [a b c d e].
- F(0) = (0 * a) + (1 * b) + (2 * c) + (3 * d) + (4 * e) = 0 + b + 2c + 3d + 4e
- F(1) = (1 * a) + (2 * b) + (3 * c) + (4 * d) + (0 * e) = a + 2b + 3c + 4d + 0
- F(2) = (2 * a) + (3 * b) + (4 * c) + (0 * d) + (1 * e) = 2a + 3b + 4c + 0 + e
Now subtracting 2 equations,
F(1) - F(0) = a + b + c + d - 4e = a + b + c + d + e - 5e
F(1) = F(0) + sum - 5e
F(2) = F(1) + sum - 5d
So,
F(k) = F(k-1) + sum - n * (( K-1)th element from end of array)
F(k) = F(k-1) + sum - n * (array(n - k))
e.g. F(b) = F(a) + sum - 5 * array[5 - 2]
Solution of after optimizaiton
public static int maxRotateFunction(int[] nums) {
int sum = 0;
int[] dp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
dp[0] += i * nums[i];
}
int maxRotate = dp[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = dp[i - 1] + sum - nums.length * nums[nums.length - i];
maxRotate = Math.max(dp[i], maxRotate);
}
return maxRotate;
}
The complexity
Time complexity: O(n)
Space complexity: O(1)