java 4ms with brief explanation


  • 0
    L
    public class Solution {
        public int maxRotateFunction(int[] A) {
            int F = 0;
            int Asum = 0;
            int count = A.length;
            for (int i=0;i<count;i++){
                F+=A[i]*i;
                Asum+=A[i];
            }
            int max=F;
            for (int j=1;j<count;j++){
                F=F+Asum-A[count-j]*count;
                max=Math.max(max,F);
            }
            return max;
        }
    }
    

    From the example, we can see that every time we rotate A, the F will be the old F0 plus sum of A (0X4->1X4, 1X3->2X3, etc) minus the last term, which is the last element in A in last step times (n-1+1). Note +1 here.


Log in to reply
 

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