Absolute Element Sums

  • + 0 comments

    JavaScript solution

    function playingWithNumbers(arr, queries) {
        // Write your code here
        let sum = 0;
        let other = [];
        arr.forEach(n => {
            if (n < -2000 || n > 2000) {
                sum += Math.abs(n);
            }
            else {
                other[n + 2000] = (other[n + 2000] || 0) + 1;
            }
        });
        let xx = 0;
        return queries.map(x => {
            xx += x;
            return other.reduce((acc, c, n) => acc + Math.abs(n - 2000 + xx) * c, sum);
        });
    }