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.
That seems to be O(n) in time and O(n) in space - you allocate array of n elements and go through it. Here is a sketch of a solution in O(m log m) time and O(m) space. Essentially what it does is go from left to right but skip cells where nothing changes.
An Operation consists of 2 numbers: index to add at and value to add. The value can be positive or negative.
* For each query (start, end, value) produce 2 operations: (start, +value) and (end + 1, -value).
* Sort all operations by index (in O(m log m))
* Create an auxiliary variable holding current sum
* Go through all operations from lowest to highest index. Aggregate all operations with equal index and add the sum of their value to current sum, obtaining next sum.
* The largest of the sequence of such obtained sums will be the solution.
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 →
That seems to be O(n) in time and O(n) in space - you allocate array of n elements and go through it. Here is a sketch of a solution in O(m log m) time and O(m) space. Essentially what it does is go from left to right but skip cells where nothing changes.
An Operation consists of 2 numbers: index to add at and value to add. The value can be positive or negative. * For each query (start, end, value) produce 2 operations: (start, +value) and (end + 1, -value). * Sort all operations by index (in O(m log m)) * Create an auxiliary variable holding current sum * Go through all operations from lowest to highest index. Aggregate all operations with equal index and add the sum of their value to current sum, obtaining next sum. * The largest of the sequence of such obtained sums will be the solution.