Maximum Number of Robots Within Budget — LeetCode 2398 Python Solution

HardQueueArrayBinary SearchPrefix SumSliding WindowMonotonic QueueHeap (Priority Queue)
Problem
#2398
Reading time
3 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview