Given an array nums
of length n
, we define a rotation function F
on nums
as follows:
F(k) = 0 * nums[k] + 1 * nums[k+1] + 2 * nums[k+2] + ... + (n-1) * nums[k+n-1]
where k
is an index in the array. k+n-1
is calculated modulo n
to ensure that it wraps around the array.
Return the maximum value of F(k)
for k
in the range 0 to n-1
.
Input: nums = [4, 3, 2, 6]
Output: 26
Explanation:
F(0) = 0*4 + 1*3 + 2*2 + 3*6 = 26
F(1) = 0*6 + 1*4 + 2*3 + 3*2 = 25
F(2) = 0*2 + 1*6 + 2*4 + 3*3 = 24
F(3) = 0*3 + 1*2 + 2*6 + 3*4 = 23
nums
is empty?
nums
always integers?
nums
is an array of integers.nums
?
S
.F(0)
.F(k)
and F(k-1)
to compute the values in O(1) time.F(k)
:
F(k) = F(k-1) + S - n * nums[n-k]
F
efficiently for each step.F
values to find the maximum.Here is a Python implementation of the optimized solution:
def maxRotateFunction(nums):
if not nums:
return 0
n = len(nums)
total_sum = sum(nums)
# Initial F(0) computation
F_0 = sum(i * nums[i] for i in range(n))
max_value = F_0
current_value = F_0
# Compute F(k) for k from 1 to n-1
for k in range(1, n):
current_value = current_value + total_sum - n * nums[-k]
max_value = max(max_value, current_value)
return max_value
# Example usage:
nums = [4, 3, 2, 6]
print(maxRotateFunction(nums)) # Output: 26
F(0)
.The total time complexity of the solution is O(n). The memory complexity is O(1), aside from the input storage, as we only use a fixed amount of additional space.
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?