You are given an integer array nums
of size n
.
The rotate function F
is defined as follows:
F(k) = 0 * nums[k] + 1 * nums[(k+1) % n] + ... + (n-1) * nums[(k+n-1) % n]
Return the maximum value of F(k)
.
The test cases are generated so that at least one valid k
exists.
nums
will have at least one element (n >= 1).nums
will fit within the range of a 32-bit integer.nums
has only one element? (F(k) should always be 0 regardless of k)nums
?F(k)
for 0 <= k < n
.F(0)
, which is the sum 0 * nums[0] + 1 * nums[1] + ... + (n-1) * nums[n-1]
.F(k)
to F(k+1)
affects the sum. We can derive that:
F(k + 1) = F(k) + sum(nums) - n * nums[n - k]
after rotating one step.F(k+1)
efficiently from F(k)
.F(k)
for all possible k
and keep track of the maximum value.#include <vector>
#include <numeric> // for accumulate
#include <algorithm> // for max
class Solution {
public:
int maxRotateFunction(std::vector<int>& nums) {
int n = nums.size();
int F = 0;
// Sum of all elements in nums
int sum_nums = accumulate(nums.begin(), nums.end(), 0);
// Calculate F(0)
for (int i = 0; i < n; ++i) {
F += i * nums[i];
}
int maxF = F;
// Calculate F(k) for k = 1 to n-1 using the observed relationship
for (int k = 1; k < n; ++k) {
F = F + sum_nums - n * nums[n - k];
maxF = std::max(maxF, F);
}
return maxF;
}
};
F(0)
): O(n), where n
is the length of nums
.F(k)
): O(1) for each k
.This results in a linear time complexity solution, which is efficient given the constraints typically observed in interview questions.
By using an efficient update relationship between successive rotations, we avoid recalculating the rotate function from scratch for each possible rotation, thus optimizing the solution to O(n) time complexity.
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?