396. Rotate Function

Problem:
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.

Analysis:
We can convert each number to A,B,C,D, then we get
F(0) = 0A + 1B + 2C +3D
F(1) = 0D + 1A + 2B +3C
F(2) = 0C + 1D + 2A +3B
F(3) = 0B + 1C + 2D +3A
From there we can conclude that
F(1) = F(0) + sum - 4D
F(2) = F(1) + sum - 4C
F(3) = F(2) + sum - 4B
then F(i) = F(i-1) + sum - n*A[n-i]
Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int maxRotateFunction(int[] A) {
        int f = 0, sum = 0, res = 0, n = A.length;
 for (int i = 0; i < n; i++) {
            sum += A[i];
            f += i*A[i];
 }

 res = f;
 for (int i = 1; i < n; i++) {
     f = f + sum - n*A[n - i];
     res = Math.max(f, res);
 }
 return res;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array