【Lintcode】1559. Take the Element and Query the Sum

記錄演算法發表於2020-11-28

題目地址:

https://www.lintcode.com/problem/take-the-element-and-query-the-sum/description

給定一個長 n n n的陣列 A A A,求 ∑ 0 ≤ i < j < n A [ i ] A [ j ] \sum_{0\le i<j<n}A[i]A[j] 0i<j<nA[i]A[j]

思路是字首和陣列。可以這樣看: ∑ 0 ≤ i < j < n A [ i ] A [ j ] = ∑ j = 1 n − 1 ( A [ j ] ∑ i = 0 j − 1 A [ i ] ) \sum_{0\le i<j<n}A[i]A[j]=\sum_{j=1}^{n-1}(A[j]\sum_{i=0}^{j-1}A[i]) 0i<j<nA[i]A[j]=j=1n1(A[j]i=0j1A[i])程式碼如下:

public class Solution {
    /**
     * @param arr: the arr
     * @return: the sum
     */
    public int takeTheElementAndQueryTheSum(int[] arr) {
        // Write your code here
        long[] preSum = new long[arr.length + 1];
        long res = 0, MOD = (long) (1E9 + 7);
        for (int i = 0; i < arr.length; i++) {
            preSum[i + 1] = preSum[i] + arr[i];
            preSum[i + 1] %= MOD;
        }
        
        for (int i = arr.length - 1; i >= 0; i--) {
            res += arr[i] * preSum[i] % MOD;
            res %= MOD;
        }
        
        return (int) res;
    }
}

時空複雜度 O ( n ) O(n) O(n)

相關文章