Leetcode——396. Rotate Function
来源:互联网 发布:网络规划设计师 必过 编辑:程序博客网 时间:2024/05/16 10:22
题目
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.
解答
原理:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]F(k-1) = 0 * Bk-1[0] + 1 * Bk-1[1] + ... + (n-1) * Bk-1[n-1] = 0 * Bk[1] + 1 * Bk[2] + ... + (n-2) * Bk[n-1] + (n-1) * Bk[0]Then,F(k) - F(k-1) = Bk[1] + Bk[2] + ... + Bk[n-1] + (1-n)Bk[0] = (Bk[0] + ... + Bk[n-1]) - nBk[0] = sum - nBk[0]Thus,F(k) = F(k-1) + sum - nBk[0]What is Bk[0]?k = 0; B[0] = A[0];k = 1; B[0] = A[len-1];k = 2; B[0] = A[len-2];...
O(N^2)和O(N)
class Solution1 {//TLEpublic: int maxRotateFunction(vector<int>& A) { if(A.size()==0) return 0; vector<int> F(A.size(),0); for(int i=0;i<A.size();i++) for(int j=0;j<A.size();j++) { F[i]=F[i]+A[(j+A.size()-i)%A.size()]*j; } int res=INT_MIN; for(int i=0;i<F.size();i++) { if(F[i]>res) res=F[i]; } return res; }};class Solution {//O(N)public: int maxRotateFunction(vector<int>& A) { int F=0,sum=0; int len=A.size(); for(int i=0;i<len;i++) { F=F+i*A[i]; sum=sum+A[i]; } int maxF=F; for(int i=len-1;i>=0;i--) { F=F+sum-len*A[i]; maxF=max(F,maxF); } return maxF; }};
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
- 2017.1.22
- Spring学习笔记 - Spring Data
- 华为机试在线训练-牛客网(5)合并表记录
- 支付宝集五福真的必须要扫描“福”字吗?
- 170123
- Leetcode——396. Rotate Function
- mybatis 中符号 #与$ 修饰变量的区别
- AndroidStudio安装
- Python与rrdtool的结合模块
- 2017.1.23
- thinkPHP5 使用laypage分页插件实现列表分页功能
- vsftpd的安装与配置
- Spring源码解析-aop
- 解决FTP下载文件时遇到的无法获取列表org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: