Store the hotel costs in the array. We’ll call the interval good if the sum of hotel costs within it does not exceed .
Let’s implement a sliding window using two indices and , and maintain it so that the current interval is good. Let be the sum of hotel costs within the interval . If s + a[j + 1] \le m, then expand the current interval to a[i ... j + 1]. Otherwise, shrink it to a[i + 1 ... j]. Find the maximum among the costs of all considered good intervals.
Example
Consider the movement of pointers for the given example.
When i = 0, j moves forward until the sum of numbers in the interval does not exceed m = 12. Stop at the interval because the sum there is equal to , while the sum in the interval is equal to .
When i = 1, we cannot move forward because the sum in the interval is equal to .
When i = 2 move forward to the interval .
The maximum value among all good intervals is equal to and is achieved in the interval .
Algorithm implementation
Read the input data.
scanf("%d %lld", &n, &m);Initialize the variables:
in , the maximum value among the costs of all processed good intervals is computed;
in , the sum of numbers in the current interval is maintained. All the numbers in the current interval are stored in the queue ;
s = res = 0;Process the hotel costs sequentially.
for (i = 0; i < n; i++)
{Read and add the cost of the current hotel to the queue.
scanf("%d", &val);
q.push(val);Update the sum within the interval. All elements of the current interval are stored in the queue .
s += val;If the sum of numbers in the current interval exceeds , we remove elements from the beginning of the interval.
while (s > m)
{
s -= q.front();
q.pop();
}Compute the maximum value among the sums of elements in good intervals (where the cost of hotels does not exceed ).
if (s > res) res = s;
}Print the answer.
printf("%lld\n", res);Python implementation
Declare a queue.
from collections import deque
q = deque()Read the input data.
n, m = map(int, input().split())
costs = list(map(int, input().split()))Initialize the variables:
in , the maximum value among the costs of all processed good intervals is computed;
in , the sum of numbers in the current interval is maintained. All the numbers in the current interval are stored in the queue ;
res = s = 0Process the hotel costs sequentially.
for val in costs:Add the cost of the current hotel to the queue.
q.append(val)Update the sum within the interval. All elements of the current interval are stored in the queue .
s += valIf the sum of numbers in the current interval exceeds , we remove elements from the beginning of the interval.
while s > m:
s -= q.popleft()Compute the maximum value among the sums of elements in good intervals (where the cost of hotels does not exceed ).
if s > res: res = sPrint the answer.
print(res)