Skip to content

Commit 0faef5e

Browse files
committed
Add solution #396
1 parent 523b448 commit 0faef5e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@
314314
393|[UTF-8 Validation](./0393-utf-8-validation.js)|Medium|
315315
394|[Decode String](./0394-decode-string.js)|Medium|
316316
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|
317+
396|[Rotate Function](./0396-rotate-function.js)|Medium|
317318
399|[Evaluate Division](./0399-evaluate-division.js)|Medium|
318319
404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy|
319320
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|

solutions/0396-rotate-function.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 396. Rotate Function
3+
* https://leetcode.com/problems/rotate-function/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums of length n.
7+
*
8+
* Assume arrk to be an array obtained by rotating nums by k positions clock-wise.
9+
* We define the rotation function F on nums as follow:
10+
* - F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
11+
*
12+
* Return the maximum value of F(0), F(1), ..., F(n-1).
13+
*
14+
* The test cases are generated so that the answer fits in a 32-bit integer.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @return {number}
20+
*/
21+
var maxRotateFunction = function(nums) {
22+
const sum = nums.reduce((a, b) => a + b, 0);
23+
let current = nums.reduce((total, n, i) => total + i * n, 0);
24+
let result = current;
25+
26+
for (let i = 1; i < nums.length; i++) {
27+
current = current + sum - nums.length * nums[nums.length - i];
28+
result = Math.max(result, current);
29+
}
30+
31+
return result;
32+
};

0 commit comments

Comments
 (0)