yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #396. Rotate Function #298

Open yokostan opened 5 years ago

yokostan commented 5 years ago

Mathematical induction problem:

class Solution {
    public int maxRotateFunction(int[] A) {
        if (A == null || A.length == 0) return 0;
        int len = A.length;
        int max = Integer.MIN_VALUE;
        int F = 0;
        int allSum = 0;
        for (int i = 0; i < len; i++) {
            F += i * A[i];
            allSum += A[i];
        }
        for (int i = len - 1; i >= 0; i--) {
            F += allSum - len * A[i];
            max = Math.max(F, max);
        }
        return max;
    }
}