Last updated on October 5th, 2024 at 06:06 pm
Here, We see Rotate Function LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Math
Companies
Amazon
Level of Question
Medium
Rotate Function LeetCode Solution
Table of Contents
Problem Statement
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.
Example 1:
Input: nums = [4,3,2,6]
Output: 26
Explanation:
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26. So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
Example 2:
Input: nums = [100]
Output: 0
1. Rotate Function LeetCode Solution C++
class Solution { public: int maxRotateFunction(vector<int>& nums) { int sum =0; int f=0; for(int i=0;i<nums.size();i++){ sum+=nums[i]; f+=i*nums[i]; } int globalSum = f; for(int i=nums.size()-1;i>0;i--){ f = f + sum -nums.size()*nums[i]; globalSum = max(f,globalSum); } return globalSum; } };
2. Rotate Function LeetCode Solution Java
class Solution { public int maxRotateFunction(int[] nums) { if (nums == null || nums.length == 0) return 0; int sum = 0, F0 = 0, max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { sum += nums [i]; F0 += i * nums [i]; } int dp [] = new int [nums.length]; dp [0] = F0; max = dp [0]; for (int i = 1; i < nums.length; i++) { dp [i] = dp [i-1] + sum - nums.length * nums [nums.length - i]; max = Math.max (max, dp [i]); } return max; } }
3. Rotate Function Solution JavaScript
var maxRotateFunction = function(nums) { const n = nums.length; let totalSum = 0; let perRoundSum = 0; for (let i = 0; i < n; i++) { totalSum += nums[i]; perRoundSum += i * nums[i]; } let answer = perRoundSum; for (let i = 1; i < n; i++) { const rotatedNum = nums[n - i]; perRoundSum = perRoundSum - (rotatedNum * (n - 1)) + (totalSum - rotatedNum); answer = Math.max(answer, perRoundSum); } return answer; };
4. Rotate Function Solution Python
class Solution(object): def maxRotateFunction(self, nums): F = 0 S = 0 for i in range(len(nums)): F = F + (nums[i] * i) S = S + nums[i] max_val = F n = len(nums) for i in range(n - 1, 0, -1): F = F + S - n * nums[i] max_val = max(max_val, F) return max_val