396. Rotate Function

這題我用了一個沒有用到數(shù)學(xué)的方法,用list滾動乘數(shù)的index去跟A相乘。其實滾動int [] A里的數(shù)字去跟index相乘也一樣,同樣要用一個list來滾動。

    public int maxRotateFunction(int[] A) {
        if (A == null || A.length == 0) return 0;
        int n = A.length;
        int max = Integer.MIN_VALUE;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(i);
        }
        for (int i = 0; i < n; i++) {
            int product = 0;
            for (int j = 0; j < n; j++) {
                product += list.get(j) * A[j];
            }
            max = Math.max(max, product);
            list.add(list.remove(0));
        }
        return max;
    }

看了答案,高票的用了一些數(shù)學(xué)方法,找了個簡單的理解了下:

   public int maxRotateFunction(int[] A) {
        if(A.length == 0){
            return 0;
        }
        
        int sum =0, iteration = 0, len = A.length;
        
        for(int i=0; i<len; i++){
            sum += A[i];
            iteration += (A[i] * i);
        }
        
        int max = iteration;
        for(int j=1; j<len; j++){
            // for next iteration lets remove one entry value of each entry and the prev 0 * k
            iteration = iteration - sum + A[j-1]*len;
            max = Math.max(max, iteration);
        }
        
        return max;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容