BRKBKS - Editorial

My brute force approach without reversing the bricks works. Can anyone tell the logic behind how this works.

https://www.codechef.com/viewsolution/33548180

what if S=1 and w1=w2=w3=2 , then answer is 6 ?