About the code used

why are we preprocessing the first k elements?What will be the problem if we process all elements together?

We are using the standard technique of sliding-window. And as the question demands the answer for subarrays of size k, we use a window of size k.

There we initially build (preprocess) the window for only size k.