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 = 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.
【问题分析】
这是一个关于数组旋转操作的题目,其他的关于Rotate 操作的题目如下:
【思路】
1. 解决这个问题的一个简单思路就是先找到Rotate点,然后把数组A划分成两部分,然后对这两部分进行有权值的求和累加。对于这个题目来说,数组A可以分成两部分:
A[0],A[1],A[2],...,A[len-k-1],A[len-k],A[ken-k+1],...,A[len-3],A[len-2],A[len-1]
我们可以先对后半部分累加求和,然后再对前半部分累加求和。
2. 思路1中的方法很简单,但是时间复杂度较高,为O(N2),如何降低时间复杂度呢?一个巧妙的方法如下:
上述方法把这个问题转换成了一个递推关系式子,只要计算一个F,则所有的F[k]都可以计算出来了,这样的计算过程时间复杂度为O(N)。
【java代码】
1 public class Solution { 2 public int maxRotateFunction(int[] A) { 3 if(A.length <= 1) return 0; 4 int maxnum = Integer.MIN_VALUE; 5 6 for(int i = 0; i < A.length; i++){ 7 maxnum = Math.max(maxnum, rotateFun(A, i)); 8 } 9 return maxnum; 10 } 11 12 public int rotateFun(int A[], int k){ 13 int len = A.length; 14 int factor = 0, sum = 0; 15 16 for(int i = k; i >= 1; i--, factor++){ 17 sum = sum + A[len-i] * factor; 18 } 19 for(int j = 0; j < len-k; j++, factor++){ 20 sum = sum + A[j] * factor; 21 } 22 return sum; 23 } 24 }
1 public class Solution { 2 public int maxRotateFunction(int[] A) { 3 int allSum = 0; 4 int len = A.length; 5 int F = 0; 6 for (int i = 0; i < len; i++) { 7 F += i * A[i]; 8 allSum += A[i]; 9 10 } 11 int max = F; 12 for (int i = len - 1; i >= 1; i--) { 13 F = F + allSum - len * A[i]; 14 max = Math.max(F, max); 15 16 } 17 return max; 18 } 19 }