<leetcode>396 Rotate Function
来源:互联网 发布:常见关联规则算法 编辑:程序博客网 时间:2024/04/27 16:41
396 Rotate Function
Given an array of integers A and letn to be its length.
Assume Bk to be an array obtained by rotating the arrayAk positions clock-wise, we define a "rotation function"F onA as follow:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
Calculate the maximum value of F(0), F(1), ..., F(n-1).
Note:
n is guaranteed to be less than 105.
Example:
A = [4, 3, 2, 6]
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.
题目解释:对于一个给定的数组,对数组进行加权求和,权重就是元素所在的索引号,然后再对数组进行顺时针旋转,也就是所有元素向右移动一位,最后一位移到最前面。求输出最大的和是多少。解题思路:一开始我想到的是用队列存放权重,然后队列元素分别与数组相乘求和,但是后来发现,这种做法简直就是暴力太愚蠢。应该从中寻找规律,我们不妨设想,所有数组元素向右移动一位会和会发生什么变化,结果我们可以看到,除了最后一位元素,所有元素的权重值都加了1,也就是和多加了A[0]+A[1]+...+A[N-2],而对于最后一位元素,被移到最前面,也就是A[n-1]的权重从(n-1)变成了0, 因此和减少了 (n-1)*A[n-1]
所以说,每一次移动的和S(new),和相对于上一次移动的和S(old)的关系如下:
S(new) = S(old) + { S - A[n-1] - (n-1)*A[n-1] } = S(old) + { S - n*A[n-1] }; // S = A[0]+A[2]+A[3]+...+A[n]
因此,每顺时针移动一位,只需要进行一次计算就好。
class Solution {public: int maxRotateFunction(vector<int>& A) { int n = A.size(); if (n == 0) return 0; int s = 0, presum = 0; for(int i = 0; i < n; i++){ s += A[i]; // S = A[0] + A[1] +...+A[n-1] presum += i * A[i]; } int MaxSum = presum; for(int i = n-1; i >= 0; i--){ presum += s - n*A[i]; // S(new) = S(old) + { S - n*A[i] }; MaxSum = max(MaxSum, presum); } return MaxSum; }};
- <leetcode>396 Rotate Function
- LeetCode 396 Rotate Function
- Leetcode 396 Rotate Function
- LeetCode #396 - Rotate Function - Easy
- 【Leetcode】396. Rotate Function
- [LeetCode]396. Rotate Function
- [Leetcode] Rotate Function
- LeetCode Rotate Function
- LeetCode : Rotate Function
- LeetCode 396. Rotate Function
- [leetcode]396. Rotate Function
- LeetCode-Rotate Function
- [LeetCode]--396. Rotate Function
- leetcode 396. Rotate Function
- [LeetCode] 396. Rotate Function
- LeetCode 396. Rotate Function
- leetcode之Rotate Function
- 45 leetcode - Rotate Function
- 在威盛学习计划
- iOS 时间比较大小
- 降价,呵呵这只是一个传说!
- Canvas 学习把玩下吧
- 咱来聊聊java的多态机制?
- <leetcode>396 Rotate Function
- 买票难难于上青天
- 根据传人的时间戳,返回格式化的时间差字符串
- 为什么要交 养老保险???
- 包管理工具使用小技巧
- 2011 絮语与寄语
- 获取系统短信
- 但通过银行
- priority_queue