Problem Link - Railway Caterers
Problem Statement
The government of Siruseri has just commissioned one of the longest and most modern railway routes in the world. This route runs the entire length of Siruseri and passes through many of the big cities and a large number of small towns and villages in Siruseri.
The railway stations along this route have all been constructed keeping in mind the comfort of the travellers. Every station has big parking lots, comfortable waiting rooms and plenty of space for eateries. The railway authorities would like to contract out the catering services of these eateries.
Unfortunately, catering contractors are not philanthropists and would like to maximise their profits. The Siruseri Economic Survey has done a through feasibility study of the different stations and documented the expected profits (or losses) for the eateries in all the railway stations on this route. Every contractor would like to run the catering service only in the profitable stations and stay away from the loss making ones.
On the other hand the authorities would like to ensure that every station was catered to. Towards this end, authorities offered to contract out stations in groups. They would fix a minimum size K and a contractor was only allowed to bid for any contiguous sequence of
K or more stations.
Approach
To solve this problem, we identify the contiguous group of K or more stations with the highest profit. Start by calculating the profit for the first K stations, which serves as the initial sum. As we move along the array, adjust the current sum by removing the station that moves out of the window and adding the one that enters. This ensures efficient tracking of the K- sized group without recalculating the entire sum. For groups larger than K, extend the current group by adding the next station’s profit while updating the maximum profit encountered. This dynamic approach maintains and updates the maximum profit for each group efficiently.
Time Complexity
The algorithm processes the list of stations in O(N), where N is the total number of stations, as we iterate through the array once.
Space Complexity
The space complexity is O(1) since only a fixed amount of extra space is used for variables.