I think this is a Dynamic Programming Question


  • 0
    R

    Since we're calculating the value of one state from previous state instead of recalculating it every time.
    Here's my code:

    public class Solution 
    {
        public int MaxRotateFunction(int[] A) 
        {
            if(A.Length == 0)
                return 0;
            
            int sum = 0;
            for(int i = 0; i < A.Length; ++i)
                sum += A[i];
            
            // Base case
            int prev = 0;
            for(int i = 0; i < A.Length; ++i)
                prev += i * A[i];
            
            int max = Math.Max(int.MinValue, prev);
            for(int i = 1; i < A.Length; ++i)
            {
                int curr = prev + sum - A.Length * A[A.Length - i];
                max = Math.Max(max, curr);
                
                prev = curr;
            }
            
            return max;
        }
    }
    

Log in to reply
 

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