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.
Wow, parallelPrefix came out to play! This was fun, here are three Java 15 solutions to optimize for 1) runtime 2) space 3) availability, respectively.
/** * Compute maximum after a series of summations. * * I. Uses a prefix sum for tractability, including the JDK's * rarely-seen "parallelPrefix" library to compute * the final summation (!). * * 𝚯(N + M) runtime for input array of size N and M queries. * 𝚯(N) space complexity * * @param n size of theoretical array * @param queries summation intervals on the array * @return maximum element of theoretical array * * https://github.com/profinite/HackerRank */publicstaticlongarrayManipulation(intn,List<List<Integer>>queries){long[]arr=newlong[n];for(List<Integer>q:queries){intleft=q.get(0),right=q.get(1),summand=q.get(2);arr[--left]+=summand;// 0-basedif(right<n)arr[right]-=summand;}Arrays.parallelPrefix(arr,Math::addExact);returnArrays.stream(arr).max().orElseThrow();}/** * II. Alternative using a prefix interval tree * to minimize space complexity. * Optimal for sparse queries and large arrays. * * 𝚯(M) runtime complexity for M queries * 𝚯(M) space complexity (rather than |N + M|) */publicstaticlongarrayManipulation2(intn,List<List<Integer>>queries){TreeMap<Integer,Long>interval=newTreeMap<>();for(List<Integer>q:queries){intleft=q.get(0),right=q.get(1);longsummand=q.get(2);interval.merge(--left,summand,Long::sum);interval.merge(right,-summand,Long::sum);// boundary}Long[]arr=interval.values().toArray(newLong[0]);Arrays.parallelPrefix(arr,Math::addExact);returnCollections.max(Arrays.asList(arr));}/** * III. 'Live' alternative using a segment tree, with the values * immediately available (no prefix sum required). But quadratic. * index -> cumulative sum * * 𝚯(M^2) runtime complexity (quadratic) */publicstaticlongarrayManipulation3(intn,List<List<Integer>>queries){TreeMap<Integer,Long>tree=newTreeMap<>();tree.put(0,0L);for(List<Integer>q:queries){intleft=q.get(0),right=q.get(1),summand=q.get(2);tree.putIfAbsent(++right,tree.lowerEntry(right).getValue());// boundary posttree.putIfAbsent(left,tree.floorEntry(left).getValue());tree.subMap(left,right).replaceAll((x,y)->y+summand);}returnCollections.max(tree.values());}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Array Manipulation
You are viewing a single comment's thread. Return to all comments →
Wow, parallelPrefix came out to play! This was fun, here are three Java 15 solutions to optimize for 1) runtime 2) space 3) availability, respectively.