4ms Java Solution with explaination, this is basically a math problem in my opinion


  • 0
    B
    public class Solution {
        public int maxRotateFunction(int[] A) {
            int n = A.length;
            if (n <= 1) {
                return 0;
            }
            int F0 = 0;//former F
            int Asum = 0;// sum of all elements in array A
            for(int i = 0; i < n; i++) {
                F0 = F0 + i*A[i];// F(0)
                Asum = Asum + A[i];
            }
            int maxF = F0; //maxF is first set to F(0)
            int F;//temp var for each F(i)
            for (int i = 1; i < n; i++) {
                F = F0 - n * A[n - i] + Asum; //F(i) = F(i-1) - n*A[n-I] +Asum  
                if (F > maxF) {
                    maxF = F;
                }
                F0 = F;
            }
            return maxF;
        }
    }
    

Log in to reply
 

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