We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I finally beated the hack. The key here is to note that, according to restrictions, there can be only 4001 different values for input, so we can characterize them by their value, and the number of occurrences for each. Then, it's pretty straightforward.
typedefuint64_tresult_t;/* This structure stores info about each element in dara `arr`. * There exist, as much, 4001 different values as * -2000 <= arr[i] <= 2000 */structpoint{intvalue;intfreq;};typedefstructpointpoint_t;/* Calculates the result of query `q` applied over arr */result_tcalculateQueryResult(size_tsample_len,point_t*restrictsample,constintq){result_tabs_sum=0;for(size_ti=0;i<sample_len;i++){abs_sum+=sample[i].freq*abs(sample[i].value+=q);}returnabs_sum;}/** This maps a value into an index of the array of samples */#define map(value) (2000 + (value))/* This builds the sample from array `arr`: values and number * of occurrences for each */voidcharacterizeSample(size_tarr_count,int*restrictarr,size_tsample_len,point_t*sample){size_ti,j;for(j=0;j<sample_len;j++){sample[j].freq=0;}for(i=0;i<arr_count;i++){j=map(arr[i]);sample[j].value=arr[i];++sample[j].freq;}}/* * Complete the 'playingWithNumbers' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER_ARRAY arr * 2. INTEGER_ARRAY queries */result_t*playingWithNumbers(size_tarr_count,int*restrictarr,size_tqueries_count,int*restrictqueries,size_t*result_count){*result_count=queries_count;// dynamically allocate space for vector `result`if(arr_count<=0||queries_count<=0){returnNULL;}result_t*result=(result_t*)calloc(queries_count,sizeof(result_t));assert(result);// initial sum of the arrayresult_tr=0;size_tj;// characterize sample: compute frequency of each valueintsample_len=4001;point_tsample[4001];characterizeSample(arr_count,arr,sample_len,sample);for(j=0;j<queries_count;j++){result[j]=calculateQueryResult(sample_len,sample,queries[j]);}returnresult;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Absolute Element Sums
You are viewing a single comment's thread. Return to all comments →
I finally beated the hack. The key here is to note that, according to restrictions, there can be only 4001 different values for input, so we can characterize them by their value, and the number of occurrences for each. Then, it's pretty straightforward.