LeetCode 396. Rotate Function
来源:互联网 发布:移动网络运营商是哪个 编辑:程序博客网 时间:2024/04/27 20:47
Given an array of integers A
and let n to be its length.
Assume Bk
to be an array obtained by rotating the array A
k positions clock-wise, we define a "rotation function" F
on A
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 = 25F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
刚开始用暴力枚举,时间复杂度O(n^2),而n<=10^5,果断超时。
没有思路了,然后参考了大神的解法。
如果向右移动一位,那么除了最后A[n-1],每个数都多加了一次,即多加了A[0]+A[1]+...+A[n-2],即sum-A[n-1];A[n-1]变成0,即减少了(n-1)*A[n-1];
所以,f(n+1)=f(n)+A[0]+A[1]+...+A[n-2]-(n-1)*A[n-1]=f(n)+sum-A[n-1]-(n-1)*A[n-1]=f(n)+n*A[n-1].
int maxRotateFunction(int* A, int ASize) { if(!ASize) return 0; int sum = 0, i; int f = 0, max; max = 1 << 31; for(i = 0; i < ASize; i ++){ sum += A[i]; f += i * A[i]; } for(i = 0; i < ASize; i ++){ f = f + sum - ASize * A[ASize - i - 1]; if(f > max) max = f; } return max;}
0 0
- 【Leetcode】396. Rotate Function
- [LeetCode]396. Rotate Function
- LeetCode 396. Rotate Function
- [leetcode]396. Rotate Function
- [LeetCode]--396. Rotate Function
- leetcode 396. Rotate Function
- [LeetCode] 396. Rotate Function
- LeetCode 396. Rotate Function
- leetcode 396. Rotate Function
- 【LeetCode】 396. Rotate Function
- LeetCode 396. Rotate Function
- LeetCode 396. Rotate Function
- [leetcode'396. Rotate Function
- LeetCode 396. Rotate Function
- [LeetCode]396. Rotate Function
- Leetcode-396. Rotate Function
- LeetCode 396. Rotate Function
- Leetcode 396. Rotate Function
- poi操作excel
- 在两个ViewController之间传输数据
- AIDL通信机制简单使用步骤
- Python笔记--String
- java之crc16测试代码
- LeetCode 396. Rotate Function
- 浏览器怪异模式和标准模式之间的区别 DTD
- 杭电OJ编码1001
- Java抽象类 详解
- 心得
- 高精度加法(重载运算符)
- 如何自定义已有架构的css样式
- 请使用-Xlint:deprecation重新编译
- leetcode-014-Longest Common Prefix