-
Notifications
You must be signed in to change notification settings - Fork 0
/
396.旋转函数.js
79 lines (76 loc) · 1.69 KB
/
396.旋转函数.js
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* @lc app=leetcode.cn id=396 lang=javascript
*
* [396] 旋转函数
*
* https://leetcode-cn.com/problems/rotate-function/description/
*
* algorithms
* Medium (53.46%)
* Likes: 220
* Dislikes: 0
* Total Accepted: 41.1K
* Total Submissions: 76.8K
* Testcase Example: '[4,3,2,6]'
*
* 给定一个长度为 n 的整数数组 nums 。
*
* 假设 arrk 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数 F 为:
*
* F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]
*
* 返回 F(0), F(1), ..., F(n-1)中的最大值 。
*
* 生成的测试用例让答案符合 32 位 整数。
*
* 示例 1:
*
* 输入: nums = [4,3,2,6]
* 输出: 26
* 解释:
* 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
* 所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
*
*
* 示例 2:
*
* 输入: nums = [100]
* 输出: 0
*
* 提示:
*
* n == nums.length
* 1 <= n <= 10^5
* -100 <= nums[i] <= 100
*
*
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number}
*/
var maxRotateFunction = function (nums) {
let fn = 0,
sum = 0,
ans = 0,
n = nums.length;
for (let i = 0; i < n; i++) {
// 求和
sum += nums[i];
// 计算 F(0)
fn += nums[i] * i;
}
ans = fn;
// 已知 F0, 从 F1 开始遍历
for (let i = 1; i < n; i++) {
// F(i) = F(i-1) + sum - n * nums[n-i]
fn = fn + sum - n * nums[n - i];
ans = Math.max(ans, fn);
}
return ans;
};
// @lc code=end