Skip to content
Advertisement

Need explanation for algorithm searching minimal large sum

I’m solving Codility questions as practice and couldn’t answer one of the questions. I found the answer on the Internet but I don’t get how this algorithm works. Could someone walk me through it step-by-step? Here is the question:

JavaScript

And here is the solution I found with my comments about parts which I don’t understand:

JavaScript

Advertisement

Answer

So what the code does is using a form of binary search (How binary search works is explained quite nicely here, https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/. It also uses an example quite similar to your problem.). Where you search for the minimum sum every block needs to contain. In the example case, you need the divide the array in 3 parts

When doing a binary search you need to define 2 boundaries, where you are certain that your answer can be found in between. Here, the lower boundary is the maximum value in the array (lower). For the example, this is 5 (this is if you divide your array in 7 blocks). The upper boundary (upper) is 15, which is the sum of all the elements in the array (this is if you divide the array in 1 block.)

Now comes the search part: In solution() you start with your bounds and mid point (10 for the example). In calculateBlockCount you count (count ++ does that) how many blocks you can make if your sum is a maximum of 10 (your middle point/ or maxSum in calculateBlockCount).
For the example 10 (in the while loop) this is 2 blocks, now the code returns this (blocks) to solution. Then it checks whether is less or more than K, which is the number of blocks you want. If its less than K your mid point is high because you’re putting to many array elements in your blocks. If it’s more than K, than your mid point is too high and you’re putting too little array elements in your array. Now after the checking this, it halves the solution space (upper = mid-1). This happens every loop, it halves the solution space which makes it converge quite quickly.

Now you keep going through your while adjusting the mid, till this gives the amount blocks which was in your input K.

So to go though it step by step:

JavaScript

Hope this helps,

Gl learning to code 🙂

Edit. When using binary search a prerequisite is that the solution space is a monotonic function. This is true in this case as when K increases the sum is strictly decreasing.

Advertisement