Rotate Function

Given an integer array nums of length n, let arr_k be nums rotated clockwise (to the right) by k positions, and define F(k) = 0 * arr_k[0] + 1 * arr_k[1] + ... + (n - 1) * arr_k[n - 1]. Return the maximum of F(0), F(1), ..., F(n - 1).

30:00

Rotate Function
medium
Free written solution
Topics
Companies

Given an integer array nums of length n, let arr_k be nums rotated clockwise (to the right) by k positions, and define F(k) = 0 * arr_k[0] + 1 * arr_k[1] + ... + (n - 1) * arr_k[n - 1]. Return the maximum of F(0), F(1), ..., F(n - 1).

Example 1:
Input: {"nums":[4,3,2,6]}
Output: 26
Constraints:
  • n=nums.lengthn = \text{nums.length}

  • 1≤n≤1051 \leq n \leq 10^5

  • −100≤nums[i]≤100-100 \leq \text{nums}[i] \leq 100

  • The answer fits in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[4,3,2,6]}

n = 4. Each rotation slides every value one slot right, and the last value wraps to slot 0. F(k) weighs each slot by its index.

arr_0 = nums rotated right by 0; F(0) = sum of weight x value

wt

val

w*v

0
4
0
1
3
3
2
2
4
3
6
18

F(k) for each rotation; best marked green

k=0k=3

total = 0

F(0) = 0

best = 0

Variables
VariableValue
n4
k0
total0
f0
best0
DepthFunction Call
Stack empty
0/10