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

题目地址:

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)

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页