Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2398: Maximum Number of Robots Within Budget

In this guide, we solve Leetcode #2398 Maximum Number of Robots Within Budget in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Queue, Array, Binary Search, Prefix Sum, Sliding Window, Monotonic Queue, Heap (Priority Queue)

Intuition

We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.

Expanding and shrinking the window lets us maintain validity without restarting the scan.

Approach

Grow the window with a right pointer, and shrink from the left only when the constraint is violated.

Track the best window as you go to keep the solution linear.

Steps:

  • Expand the right end of the window.
  • While invalid, move the left end to restore constraints.
  • Update the best window found.

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. To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25. It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.

Python Solution

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

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n), where nnn is the number of robots in the problem. The space complexity is O(n)O(n)O(n), where nnn is the number of robots in the problem.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy