leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit bedd45bbdb069ba6bcc4df16577bd6fd2e2c1a1d
parent ab95956f801403524c6fd1f7d6a904f5b26cadeb
Author: Jack Sangdahl <jack@pngu.org>
Date:   Thu, 30 Apr 2026 18:51:01 -0600

396. rotate function

Diffstat:
Arotate_function.c | 35+++++++++++++++++++++++++++++++++++
Arotate_function.py | 29+++++++++++++++++++++++++++++
2 files changed, 64 insertions(+), 0 deletions(-)

diff --git a/rotate_function.c b/rotate_function.c @@ -0,0 +1,35 @@ +// 396. Rotate Function +#include "leetcode.h" + +/* + * you are given an integer array 'nums' of length 'n'. assume 'arr_k' to be an + * array obtained by rotating 'nums' by 'k' positions clockwise. we define the + * rotation function 'F' on 'nums' as follows: 'F(k) = 0 * arr_k[0] + 1 * + * arr_k[1] + ... + (n - 1) * arr_k[n - 1]'. return the maximum value of 'F(0), + * F(1), ..., F(n - 1)'. the test cases are generated such that the answer fits + * in a 32-bit integer. + */ + +int maxRotateFunction(int *nums, int numsSize) { + int f = 0, sum = 0; + for (int i = 0; i < numsSize; i++) { + f += i * nums[i]; + sum += nums[i]; + } + int ans = f; + for (int i = numsSize - 1; i > 0; i--) { + f += sum - numsSize * nums[i]; + ans = fmax(ans, f); + } + return ans; +} + +int main() { + int n1[] = {4, 3, 2, 6}, n2[] = {100}; + int r1 = maxRotateFunction(n1, ARRAY_SIZE(n1)); + int r2 = maxRotateFunction(n2, ARRAY_SIZE(n2)); + printf("%d\n", r1); + assert(r1 == 26); + printf("%d\n", r2); + assert(r2 == 0); +} diff --git a/rotate_function.py b/rotate_function.py @@ -0,0 +1,29 @@ +# 396. Rotate Function +from typing import List + +""" +you are given an integer array 'nums' of length 'n'. assume 'arr_k' to be an +array obtained by rotating 'nums' by 'k' positions clockwise. we define the +rotation function 'F' on 'nums' as follows: 'F(k) = 0 arr_k[0] + 1 +arr_k[1] + ... + (n - 1) arr_k[n - 1]'. return the maximum value of 'F(0), +F(1), ..., F(n - 1)'. the test cases are generated such that the answer fits +in a 32-bit integer. +""" + + +class Solution: + def maxRotateFunction(self, nums: List[int]) -> int: + f, n, total = 0, len(nums), sum(nums) + for i, j in enumerate(nums): + f += i * j + ans = f + for i in range(n - 1, 0, -1): + f += total - n * nums[i] + ans = max(ans, f) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxRotateFunction(nums=[4, 3, 2, 6])) + print(obj.maxRotateFunction(nums=[100]))