396. Rotate Function

  • 31.2%

https://leetcode.com/problems/rotate-function/description/

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.

1
2
3
4
5
6
7
8
9
10
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.

方法一:

我的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
int sum = accumulate(A.begin(), A.end(), 0);
int res, cur=0;
int n = A.size();
for(int i=0; i<n; i++)
cur += i*A[i];
res = cur;
for(int i=n-1; i>0; i--){
cur = cur+sum - n*A[i];
res = max(cur, res);
}
return res;
}
};

方法二:

使用long long

13ms, September 12, 2016

https://discuss.leetcode.com/topic/58293/c-solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
if(A.size()==0) return 0;

long long allsum = 0;
long long sum2 = 0;
for(int i = 0; i < A.size(); i++){
allsum += A[i] * i;
sum2 += A[i];
}

long long result = allsum;
for(int i=0; i<A.size(); i++){
allsum -= sum2;
allsum += A[i];
allsum += A[i] * int(A.size() - 1);
result = max(allsum, result);
}
return result;
}
};

python

52ms, September 12, 2016

https://discuss.leetcode.com/topic/58310/6-lines-python-53ms-solution-use-f-n-to-get-f-n-1

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A : return 0
maxres = tmp = sum([i*A[i] for i in xrange(len(A))])
tot, index = sum(A), -1
for index in xrange(-1, -len(A)-1, -1):
maxres, tmp = max(maxres, tmp), tmp+tot-(len(A)*A[index])
return maxres

java

4ms, September 12, 2016

https://discuss.leetcode.com/topic/58302/java-solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int maxRotateFunction(int[] A) {
int n = A.length;
int sum = 0;
int candidate = 0;

for(int i = 0; i < n; i++){
sum += A[i];
candidate += A[i] * i;
}
int best = candidate;

for(int i=n-1; i>0; i--){
candidate = candidate + sum - A[i] * n;
best = Math.max(best, candidate);
}
return best;
}
}
谢谢你,可爱的朋友。