Absolute Element Sums


Problem Statement :


Given an array of integers, you must answer a number of queries. Each query consists of a single integer, , and is performed as follows:

Add  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.
Tip: The Input/Output for this challenge is very large, so you'll have to be creative in your approach to pass all test cases.

Function Description

Complete the playingWithNumbers function in the editor below. It should return an array of integers that represent the responses to each query.

playingWithNumbers has the following parameter(s):

arr: an array of integers
queries: an array of integers

Input Format

The first line contains an integer  the number of elements in .
The second line contains  space-separated integers .
The third line contains an integer , the number of queries.
The fourth line contains  space-separated integers  where .

Output Format

For each query, print the sum of the absolute values of all the array's elements on a new line.



Solution :



title-img


                            Solution in C :

In  C  :






#include <stdio.h>
#include <stdlib.h>
void sort_a(int*a,int size);
void merge(int*a,int*left,int*right,int left_size, int right_size);
int get_i(int*a,int num,int size);
int med(int*a,int size);
int a[500000],sum[500000];

int main(){
  int N,Q,offset=0,x,i;
  long long ans;
  scanf("%d",&N);
  for(i=0;i<N;i++)
    scanf("%d",a+i);
  sort_a(a,N);
  for(i=1,sum[0]=a[0];i<N;i++)
    sum[i]=sum[i-1]+a[i];
  scanf("%d",&Q);
  while(Q--){
    scanf("%d",&x);
    offset+=x;
    i=get_i(a,-offset+1,N);
    if(!i)
      ans=sum[N-1]+offset*(long long)N;
    else
      ans=sum[N-1]-2*sum[i-1]+offset*(long long)(N-2*i);
    printf("%lld\n",ans);
  }
  return 0;
}
void sort_a(int*a,int size){
  if (size < 2)
    return;
  int m = (size+1)/2,i;
  int *left,*right;
  left=(int*)malloc(m*sizeof(int));
  right=(int*)malloc((size-m)*sizeof(int));
  for(i=0;i<m;i++)
    left[i]=a[i];
  for(i=0;i<size-m;i++)
    right[i]=a[i+m];
  sort_a(left,m);
  sort_a(right,size-m);
  merge(a,left,right,m,size-m);
  free(left);
  free(right);
  return;
}
void merge(int*a,int*left,int*right,int left_size, int right_size){
    int i = 0, j = 0;
    while (i < left_size|| j < right_size) {
        if (i == left_size) {
            a[i+j] = right[j];
            j++;
        } else if (j == right_size) {
            a[i+j] = left[i];
            i++;
        } else if (left[i] <= right[j]) {
            a[i+j] = left[i];
            i++;                
        } else {
            a[i+j] = right[j];
            j++;
        }
    }
    return;
}
int get_i(int*a,int num,int size){
  if(size==0)
    return 0;
  if(num>med(a,size))
    return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
  else
    return get_i(a,num,(size-1)>>1);
}
int med(int*a,int size){
  return a[(size-1)>>1];
}
                        


                        Solution in C++ :

In C++  :







#include<bits/stdc++.h>

#define s(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define ss(a) scanf("%s",a)

#define MP           make_pair
#define PB           push_back
#define REP(i, n)    for(int i = 0; i < n; i++)
#define INC(i, a, b) for(int i = a; i <= b; i++)
#define DEC(i, a, b) for(int i = a; i >= b; i--)
#define CLEAR(a)     memset(a, 0, sizeof a)

using namespace std;

typedef long long          LL;
typedef unsigned long long ULL;
typedef vector<int>        VI;
typedef pair<int, int>     II;
typedef vector<II>         VII;

LL inp[500005];
LL cum[500005];
int main()
{
      int t=1;
      //s(t);
      while(t--)
      {
            int n,Q,q;
            LL add = 0;
            s(n);
            REP(i,n)
                  sl(inp[i]);
            sort(inp,inp+n);
            cum[0] = inp[0];
            INC(i,1,n-1)
                  cum[i] = cum[i-1]+inp[i];
            s(Q);
            while(Q--)
            {
                  s(q);
                  add+=q;
                  int pos = lower_bound(inp,inp+n,-add)-inp;
                  LL ans;
                  if(pos>0)
                        ans = (cum[n-1]-cum[pos-1]+add*(n-pos))-(cum[pos-1]+add*pos);
                  else 
                        ans = (cum[n-1]+add*n);
                  printf("%lld\n",ans);
            }
      }
      return 0;
}
                    


                        Solution in Java :

In   Java :






import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class C {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve()
	{
		int n = ni();
		long[] a = new long[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		Arrays.sort(a);
		long[] cum =new long[n+1];
		for(int i = 0;i < n;i++){
			cum[i+1] = cum[i] + a[i];
		}
		long h = 0;
		for(int Q = ni();Q >= 1;Q--){
			int x = ni();
			h -= x;
			int ind = Arrays.binarySearch(a, h);
			if(ind < 0)ind = -ind-2;
			long ret = 0;
			ret += cum[n]-cum[ind+1]-h*(n-(ind+1));
			ret += -cum[ind+1]+h*(ind+1);
			out.println(ret);
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
		
		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}
	
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;
	
	private static int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
	
	private static double nd() { return Double.parseDouble(ns()); }
	private static char nc() { return (char)skip(); }
	
	private static String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private static char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private static char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private static int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
                    


                        Solution in Python : 
                            
from collections import Counter

def q(arr, queries):
    positive_n = [el for el in arr if el >= 0]
    negative_n = [el for el in arr if el <  0]
    pos_size = len(positive_n)
    neg_size = len(negative_n)
    positive = list(reversed(sorted(Counter(positive_n).items())))
    negative = sorted(Counter(negative_n).items())
    tot = sum(abs(el) for el in arr)
    diff = 0  # cum sum of queries
    for q in queries:
        diff += q
        tot += pos_size * q - neg_size * q
        if q > 0:
            while neg_size and negative[-1][0] + diff >= 0:
                (n, count) = negative.pop()
                positive.append((n, count))
                pos_size += count
                neg_size -= count
                tot += abs(n + diff) * 2 * count
        else:
            while pos_size and positive[-1][0] + diff < 0:
                (n, count) = positive.pop()
                negative.append((n, count))
                neg_size += count
                pos_size -= count
                tot += abs(n + diff) * 2 * count
        yield tot

input()
arr = [int(s) for s in input().split()]

input()
que = [int(s) for s in input().split()]

for res in q(arr, que):
    print(res)
                    


View More Similar Problems

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →