396. Rotate Function Medium

@problem@discussion
#Array#Math#Dynamic Programming



1/**
2 * [396] Rotate Function
3 *
4 * You are given an integer array nums of length n.
5 * 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:
6 * 
7 * F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
8 * 
9 * Return the maximum value of F(0), F(1), ..., F(n-1).
10 * The test cases are generated so that the answer fits in a 32-bit integer.
11 *  
12 * Example 1:
13 * 
14 * Input: nums = [4,3,2,6]
15 * Output: 26
16 * Explanation:
17 * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
18 * F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
19 * F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
20 * F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
21 * So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
22 * 
23 * Example 2:
24 * 
25 * Input: nums = [100]
26 * Output: 0
27 * 
28 *  
29 * Constraints:
30 * 
31 * n == nums.length
32 * 1 <= n <= 10^5
33 * -100 <= nums[i] <= 100
34 * 
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/rotate-function/
39// discuss: https://leetcode.com/problems/rotate-function/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42use std::cmp;
43impl Solution {
44    pub fn max_rotate_function(nums: Vec<i32>) -> i32 {
45        let (mut sum, mut current) = (0, 0);
46        for (i, n) in nums.iter().enumerate() {
47            sum += n;
48            current += *n * i as i32;
49        }
50
51        let mut max = current;
52        for i in 1..nums.len() {
53            current += nums[i - 1] * nums.len() as i32 - sum;
54            max = cmp::max(max, current);
55        }
56        max
57    }
58}
59
60// submission codes end
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_396() {
68        assert_eq!(Solution::max_rotate_function(vec![4,3,2,6]), 26);
69        assert_eq!(Solution::max_rotate_function(vec![]), 0);
70    }
71}
72


Back
© 2025 bowen.ge All Rights Reserved.