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.
Here is the solution in js in O(M+N). The key is to understand you can represent the list of N elements as a prefix sum array. Once you have the prefix array that represents the actual list, you can just scan that array to find the max sum
functionprocessData(input){//Enter your code here// parse input into a friendly format to work wtiharr=input.split('\n');arr=arr.map(function(element){returnelement.split(' ').map(Number);});// initialize n and m from input arrayn=arr[0][0];m=arr[0][1];// create an array of length n + 1, all zeroscontainer=Array(n+1).fill(0)// run-time was too long when I created the container array via looping/* container = [0]; for(var i =0; i < n; i++) container.push(0); */// loop through m operations and create prefix sum arrayfor(vari=1;i<=m;i++){//arr[i] = arr[i].split(' ').map(Number);container[arr[i][0]-1]+=arr[i][2];container[arr[i][1]]-=arr[i][2];}max=0;temp_max=0;// scan the prefix sum array, and then return the max sumfor(vari=0;i<container.length;i++){temp_max+=container[i];max=Math.max(max,temp_max);}console.log(max);}
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 →
Here is the solution in js in O(M+N). The key is to understand you can represent the list of N elements as a prefix sum array. Once you have the prefix array that represents the actual list, you can just scan that array to find the max sum