396. Rotate Function

分手后的思念是犯贱 2022-07-15 01:38 231阅读 0赞

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:

  1. A = [4, 3, 2, 6]
  2. F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
  3. F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
  4. F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
  5. F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
  6. So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
  7. public class Solution {
  8. public int maxRotateFunction(int[] A) {
  9. if(A.length==0)
  10. return 0;
  11. int max = Integer.MIN_VALUE;
  12. for(int i=0;i<A.length;i++)
  13. if(F(A,i)>max)
  14. max = F(A,i);
  15. return max;
  16. }
  17. public int F(int[] A, int k) {
  18. int res = 0, count = 0;
  19. for (int i = A.length - k; i < A.length; i++)
  20. res += A[i] * count++;
  21. for (int i = 0; i < A.length - k; i++)
  22. res += A[i] * count++;
  23. return res;
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读

    相关 translate与rotate

    今天在做旋转动画时,发现translate与rotate的顺序会对效果产生影响, 在此之前我以为顺序可以随便放的 理想情况是绕球体旋转,效果如下图 ![在这里插入图片