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 came up with the same solution in Javascript. The interesting thing about it is that JS Arrays are actually hashmaps and are sparse, so you don't end up iterating over N items if there are only a few spans. (E.g. if there is an element at arr[1] and another at arr[10000], arr.forEach will only perform two iterations.). For this reason, I'm careful NOT to initialize array elements and to check for undefined before adding the addend in order to minimize the number of elements in the array. After reading the op-ed, I think this is equivalent to their optimal solution.
(Interestingly, if one prints the array alone with console.log(), it handles sparsness gracefully, but if you concatenate to another string with the + operator, it will print out all of the undefined elements individually.)
Also note the single loop for adding up the diffs and finding the max without any extra variables outside the loop. (Trying to be functional.)
I'm new to JS, so be gentle. Style advice for an old Java 2 progammer is welcome.
Array Manipulation
You are viewing a single comment's thread. Return to all comments →
I came up with the same solution in Javascript. The interesting thing about it is that JS Arrays are actually hashmaps and are sparse, so you don't end up iterating over N items if there are only a few spans. (E.g. if there is an element at arr[1] and another at arr[10000], arr.forEach will only perform two iterations.). For this reason, I'm careful NOT to initialize array elements and to check for undefined before adding the addend in order to minimize the number of elements in the array. After reading the op-ed, I think this is equivalent to their optimal solution.
(Interestingly, if one prints the array alone with console.log(), it handles sparsness gracefully, but if you concatenate to another string with the + operator, it will print out all of the undefined elements individually.)
Also note the single loop for adding up the diffs and finding the max without any extra variables outside the loop. (Trying to be functional.)
I'm new to JS, so be gentle. Style advice for an old Java 2 progammer is welcome.