• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Absolute Element Sums – HackerRank Solution

Absolute Element Sums - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 25, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Absolute Element Sums – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Absolute Element Sums HackerRank Solution
  • Java Absolute Element Sums HackerRank Solution
  • Python 3 Absolute Element Sums HackerRank Solution
  • Python 2 Absolute Element Sums HackerRank Solution
  • C Absolute Element Sums HackerRank Solution
    • Leave a comment below
      • Related posts:

Absolute Element Sums – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ Absolute Element Sums HackerRank Solution


Copy Code Copied Use a different Browser

#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#include <limits>
#include <functional>
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#if defined(_MSC_VER) || __cplusplus > 199711L
#define aut(r,v) auto r = (v)
#else
#define aut(r,v) __typeof(v) r = (v)
#endif
#define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it)
#define all(o) (o).begin(), (o).end()
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define mset(m,v) memset(m,v,sizeof(m))
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef vector<int> vi; typedef pair<int,int> pii; typedef vector<pair<int,int> > vpii; typedef long long ll;
template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

int main() {
	int N;
	scanf("%d", &N);
	vector<long long> A(N);
	rep(i, N) scanf("%lld", &A[i]);
	sort(all(A));
	vector<long long> sum(N+1, 0);
	rep(i, N)
		sum[i+1] = sum[i] + A[i];
	int Q;
	scanf("%d", &Q);
	long long added = 0;
	rep(ii, Q) {
		int x;
		scanf("%d", &x);
		added += x;
		//A[i] + added >= 0
		//A[i] >= -added
		int k = lower_bound(all(A), -added) - A.begin();
		long long ans = 0;
		ans += (sum[N] - sum[k]) + added * (N - k);
		ans += -((sum[k] - sum[0]) + added * k);
		printf("%lld\n", ans);
	}
	return 0;
}


Java Absolute Element Sums HackerRank Solution


Copy Code Copied Use a different Browser

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)); }
}

 


Python 3 Absolute Element Sums HackerRank Solution


Copy Code Copied Use a different Browser

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)


Python 2 Absolute Element Sums HackerRank Solution


Copy Code Copied Use a different Browser

# Enter your code here. Read input from STDIN. Print output to STDOUT

input()
array = map(int, raw_input().split(" "))
input()
queries = map(int, raw_input().split(" "))
buckets = [0] * 4001
shift = 0
for i in array:
    buckets[i + shift + 2000] += 1 # buckets from -2000 to 2000
for q in queries:
    shift += q
    if shift - q >= 2000 and shift >= 2000:
        s += q * len(array)
    elif shift - q <= -2000 and shift <= -2000:
        s -= q * len(array)
    else:
        s = 0
        for i, y in enumerate(buckets):
            val = i + shift - 2000
            s += y * abs(val)
    print s


C Absolute Element Sums HackerRank Solution


Copy Code Copied Use a different Browser

#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];
}

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPlus Minus – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMini-Max Sum – HackerRank Solution
Tags: Absolute Element SumsCc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Almost Integer Rock Garden - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Sorted Subsegments - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPlus Minus – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMini-Max Sum – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions
Code Solutions

Can Place Flowers – LeetCode Solution

September 11, 2022
28
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Revising Aggregations – Averages EasySQL (Basic) – SQL – HackerRank Solution

May 30, 2022
0
Leetcode All Problems Solutions
Code Solutions

Contiguous Array – LeetCode Solution

September 10, 2022
10
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Team Formation – HackerRank Solution

May 27, 2022
686

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?