美文网首页计算机Leetcode, again
Leetcode - Rotate Function

Leetcode - Rotate Function

作者: Richardo92 | 来源:发表于2016-10-13 06:09 被阅读6次

    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

    相关文章

      网友评论

        本文标题:Leetcode - Rotate Function

        本文链接:https://www.haomeiwen.com/subject/zjhwyttx.html