I was trying to solve this problem on Hackerrank. https://www.hackerrank.com/challenges/playing-with-numbers/problem
Given an array of integers, you must answer a number of queries. Each query consists of a single integer, x, and is performed as follows:
- Add x to each element of the array, permanently modifying it for any future queries.
- Find the absolute value of each element in the array and print the sum of the absolute values on a new line.
Can someone explain this solution to me?
I didn't quite understand the need to search for -q
in the array n = bisect_left(arr, -q)
and this line (Sc[-1] - 2 * Sc[n] + q * (N - 2 * n)
.
from bisect import bisect_left
def playingWithNumbers(arr, queries):
N = len(arr)
res = []
# Calculate cummulative sum of arr
arr = sorted(arr)
Sc = [0]
for x in arr:
Sc.append(x+Sc[-1])
q = 0
for x in queries:
q += x
n = bisect_left(arr, -q)
res.append((Sc[-1] - 2 * Sc[n] + q * (N - 2 * n)))
return res
Thank you