Problem Description
Given two arrays, chargeTimes and runningCosts, representing the charging cost and running cost for each robot respectively, and an integer budget, determine the maximum number of consecutive robots that can be operated without exceeding the budget. The total cost for a group of robots is defined as the maximum charge time of the group plus the group size multiplied by the sum of their running costs.
Key Insights
- Use a sliding window to consider consecutive robots.
- Maintain the sum of runningCosts in the current window.
- Use a monotonic deque (max queue) to keep track of the maximum chargeTime in the current window efficiently.
- Expand the window by moving the right pointer and, when the cost exceeds the budget, shrink the window by moving the left pointer.
- The cost formula is: currentMaxCharge + windowSize * currentSumRunningCosts <= budget.
Space and Time Complexity
Time Complexity: O(n) – Each element is processed at most twice (once when added and once when removed from the window/deque). Space Complexity: O(n) – In the worst case, the deque can store all indices.
Solution
The solution uses a sliding window approach along with a monotonic deque to efficiently determine the maximum charge time in the current window. For each new index added:
- Add the new robot's running cost to the running sum.
- Remove elements from the deque’s back if they are less than the current robot's charge time; this maintains a decreasing order.
- Append the current index to the deque.
- While the total cost (max charge from deque’s front + window length * running sum) exceeds the budget, move the left pointer of the window to shrink it. If the left pointer equals the index at the front of the deque, pop it from the deque.
- Throughout the process, track the maximum window length that satisfies the cost condition.