Maximum Number of Robots Within Budget — LeetCode 2398 Python Solution
HardQueueArrayBinary SearchPrefix SumSliding WindowMonotonic QueueHeap (Priority Queue)
- Problem
- #2398
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n.
Example
- Input
- chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25
- Output
- 3
- Explanation
- It is possible to run all individual and consecutive pairs of robots within budget.
Python solution
Python
class Solution:
def maximumRobots(
self, chargeTimes: List[int], runningCosts: List[int], budget: int
) -> int:
q = deque()
ans = s = l = 0
for r, (t, c) in enumerate(zip(chargeTimes, runningCosts)):
s += c
while q and chargeTimes[q[-1]] <= t:
q.pop()
q.append(r)
while q and (r - l + 1) * s + chargeTimes[q[0]] > budget:
if q[0] == l:
q.popleft()
s -= runningCosts[l]
l += 1
ans = max(ans, r - l + 1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of robots in the problem auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2398. Maximum Number of Robots Within Budget is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 862Shortest Subarray with Sum at Least KHardLeetCode 209Minimum Size Subarray SumMediumLeetCode 713Subarray Product Less Than KMediumLeetCode 1004Max Consecutive Ones IIIMediumLeetCode 2106Maximum Fruits Harvested After at Most K StepsHardLeetCode 2302Count Subarrays With Score Less Than KHard
Frequently asked questions
- How hard is LeetCode 2398. Maximum Number of Robots Within Budget?
- LeetCode 2398. Maximum Number of Robots Within Budget is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2398. Maximum Number of Robots Within Budget?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2398. Maximum Number of Robots Within Budget?
- The Python solution on this page uses O(n), where n is the number of robots in the problem auxiliary space.
- What topics does LeetCode 2398. Maximum Number of Robots Within Budget cover?
- LeetCode 2398. Maximum Number of Robots Within Budget is tagged Queue, Array, Binary Search, Prefix Sum, Sliding Window, Monotonic Queue and Heap (Priority Queue) on LeetCode.