/**
* Problem: LeetCode 396 - Rotate Function
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int maxRotateFunction(int[] nums) {
int n = nums.length;
long totalSum = 0;
long currentF = 0;
for (int i = 0; i < n; i++) {
totalSum += nums[i];
currentF += (long) i * nums[i];
}
long maxF = currentF;
for (int k = 1; k < n; k++) {
currentF += totalSum - (long) n * nums[n - k];
maxF = Math.max(maxF, currentF);
}
return (int) maxF;
}
}
"""
Problem: LeetCode 396 - Rotate Function
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
n = len(nums)
total_sum = sum(nums)
current_f = sum(i * val for i, val in enumerate(nums))
max_f = current_f
for k in range(1, n):
current_f += total_sum - n * nums[n - k]
if current_f > max_f:
max_f = current_f
return max_f
/**
* Problem: LeetCode 396 - Rotate Function
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
/**
* Problem: LeetCode 396 - Rotate Function
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int maxRotateFunction(vector<int>& nums) {
int n = nums.size();
long long totalSum = 0;
long long currentF = 0;
for (int i = 0; i < n; i++) {
totalSum += nums[i];
currentF += 1LL * i * nums[i];
}
long long maxF = currentF;
for (int k = 1; k < n; k++) {
currentF += totalSum - 1LL * n * nums[n - k];
maxF = max(maxF, currentF);
}
return static_cast<int>(maxF);
}
};
/**
* Problem: LeetCode 396 - Rotate Function
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var maxRotateFunction = function(nums) {
const n = nums.length;
let totalSum = 0;
let currentF = 0;
for (let i = 0; i < n; i++) {
totalSum += nums[i];
currentF += i * nums[i];
}
let maxF = currentF;
for (let k = 1; k < n; k++) {
currentF += totalSum - n * nums[n - k];
if (currentF > maxF) {
maxF = currentF;
}
}
return maxF;
};