396. Rotate Function

一开始没察觉到0123 3012 2301 而不是 0123 1230 2301 的原因,所以也没找到规律,一怒之下brute-force..

public int maxRotateFunction(int[] A) 
    {
        if(A.length == 0) return 0;
        
        int res = Integer.MIN_VALUE;
        for(int i = 0; i < A.length;i++)
        {
            int temp = 0;
            for(int j = i,total = 0; total < A.length; j++,total++)
            {
                
                temp += A[j] * total;
                
                if(j == A.length -1) j = -1;
            }
            res = Math.max(res,temp);
        }
        
        return res;
       
    }

昨晚发现是Easy难度的题,那肯定有特殊的办法,于是单击Discuss.发现新结果可以基于上一个结果。

拿 |4 3 2| 6 来说,第一次变动之后
6 |4 3 2|
4 3 2 比上一个循环各多加了1次(40+31+23 => 41+32+23), 在计算完 4 3 2 6的基础上,加一次数组和。此时我们多加了的一个数是6*4,因为这里6被转到前面,和0乘了,所以要减掉。

总之 newRes = preRes + sumOfArray - A[0]*(A.length)

public int maxRotateFunction(int[] A) 
    {
        if(A.length == 0) return 0;
        
        int res = 0;
        int sum = 0;
        for(int i = 0; i < A.length; i++)
        {
            sum+=A[i];
            res +=A[i]*i;
        }
        
        int max = res;
        for(int i = 1; i < A.length; i++)
        {
            res = res + sum - A[A.length-i]*(A.length);
            max = Math.max(res,max);
        }
        
        return max;
       
    }

Array操作的平移,也算学到点新东西。

原文地址:https://www.cnblogs.com/reboot329/p/5867600.html