Skip to main content
Back to problems
#396
Medium Algorithms

Rotate function

Array Math Dynamic Programming
45.4% acceptance
Jan 12, 2026
1676
280
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_rotate_function(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let sum: i32 = nums.iter().sum();
    let mut f = 0;
    
    for i in 0..n {
      f += i as i32 * nums[i];
    }
    
    let mut max_f = f;
    
    for i in 1..n {
      f = f + sum - n as i32 * nums[n - i];
      max_f = max_f.max(f);
    }
    
    max_f
  }
}