8 line C++ solution


  • 0
    R

    While the brute force solution is O(n^2), this problem can be easily solved in O(n) by observing the pattern for each function F(i) can be computed from F(i-1) using the following:

    F[i] = F[i-1] + Sum(A[i..n]) - n * A[i]
    
    class Solution {
    public:
        int maxRotateFunction(vector<int>& A) {
            int s = 0, f = 0;
            for(int i=0; i< A.size(); i++) { s+= A[i]; f+= i*A[i]; }
            int max = f;
            for (int i = A.size()-1; i>=0; i--)
            {
                f = f + s - A.size() * A[i];
                max = max > f ? max : f;
            }
            return max;
        }
    };
    

Log in to reply
 

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