Java O(n) solution with description


  • 0
    K

    Each iteration will minus sum of the array and then add array length * the element that times zero in the previous iteration.
    '''
    public int maxRotateFunction(int[] A) {
    if (A == null || A.length == 0)
    return 0;
    int len = A.length;
    int sum = 0;
    int result = 0;
    for (int i = 0; i < len; i++) {
    sum += A[i];
    result += i*A[i];
    }
    int tmp = result;
    for (int i = 1; i < len; i++) {
    tmp += (A[i-1]*len - sum);
    result = Math.max(result, tmp);
    }
    return result;
    }
    '''


Log in to reply
 

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