r/programmingchallenges • u/mr-rusof • Jul 02 '18
The Watermark Problem
http://ruslanledesma.com/2018/07/01/the-watermark-problem.html
3
Upvotes
r/programmingchallenges • u/mr-rusof • Jul 02 '18
View all comments
Show parent comment
1
u/lrflew Jul 03 '18
It's true that the runtime performance of the code I posted is O(n2) thanks to the
h[..].maxinside themapcall. It is pretty simple to make this general method O(n), though, by computing theh[0..i].maxandh[i..-1].maxvalues into arrays for eachi(let's call themleftandrightrespectively). By computingleftin increasing values fori, you can make use of the fact thatleft[i] = h[0..i].max = [h[0..(i-1)].max, h[i]].max = [left[i-1], h[i]].maxto generate the array in O(n). You can do the same for right, but going the other way (using[right[i+1], h[i]].max). This method is still (probably) generally slower than yours, and has a space complexity of O(n) (while I think yours is O(1) ignoring the input array). Either way, I still think that the brevity and simplicity of this solution is more important for this kind of "random programming challenge" than performance (especially if it's never going to be production code).If you want to see this method working in O(n), here is my implementation in Java. I didn't post it originally because it's quite a bit more verbose, and it doesn't seem to pass the site's checker. I'm not sure if it's my code or the tester, though, as it didn't give me the test case that failed. If you figure out what's wrong, let me know.