title: Absolute Elements Sums
body: <p>I was trying to solve this problem on Hackerrank.
  <a href="https://www.hackerrank.com/challenges/playing-with-numbers/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/playing-with-numbers/problem</a></p>
  
  <p>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: </p>
  
  <ul>
  <li>Add x to each element of the array, permanently modifying it for any future queries.</li>
  <li>Find the absolute value of each element in the array and print the sum of the absolute values on a new line.</li>
  </ul>
  
  <p>Can someone explain this solution to me? <br/>
  I didn't quite understand the need to search for <code>-q</code> in the array <code>n = bisect_left(arr, -q)</code> and this line <code>(Sc[-1] - 2 * Sc[n] + q * (N - 2 * n)</code>. </p>
  
  <pre><code>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
  </code></pre>
  
  <p>Thank you</p>