-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0396-rotate-function.js
More file actions
26 lines (21 loc) · 1.08 KB
/
0396-rotate-function.js
File metadata and controls
26 lines (21 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Rotate Function
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var maxRotateFunction = function (nums) {
const numElementsInArray = nums.length;
if (numElementsInArray === 0) {
return 0;
}
const totalArraySum = nums.reduce((sumAccumulator, currentArrayValue) => sumAccumulator + currentArrayValue, 0);
let initialRotationSummation = nums.reduce((fZeroAccumulator, arrayElementValue, arrayElementIndex) => fZeroAccumulator + arrayElementIndex * arrayElementValue, 0);
let maxFunctionValue = initialRotationSummation;
let currentCalculatedFunctionValue = initialRotationSummation;
for (let rotationIterationStep = 1; rotationIterationStep < numElementsInArray; rotationIterationStep++) {
const lastElementInPreviousRotation = nums[numElementsInArray - rotationIterationStep];
currentCalculatedFunctionValue = currentCalculatedFunctionValue + totalArraySum - numElementsInArray * lastElementInPreviousRotation;
maxFunctionValue = Math.max(maxFunctionValue, currentCalculatedFunctionValue);
}
return maxFunctionValue;
};