Java O(n)


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.