计算机Leetcode, again

Leetcode - Rotate Function

2016-10-13  本文已影响6人  Richardo92

My code:

public class Solution {
    public int maxRotateFunction(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int sum = 0;
        int iteration = 0;
        
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            iteration += i * A[i];
        }
        
        int max = iteration;
        for (int i = 1; i < A.length; i++) {
            iteration = iteration - sum + A[i - 1] * A.length;
            max = Math.max(max, iteration
            );
        }
        
        return max;
    }
}

reference:
https://discuss.leetcode.com/topic/58616/java-solution-o-n-with-non-mathametical-explaination

一开始超时了。后来看了答案,发现是可以用递推公式的,还是太急了,一点不会就看答案。

Anyway, Good luck, Richardo! -- 10/12/2016

上一篇下一篇

猜你喜欢

热点阅读