#2398

Maximum Number of Robots Within Budget

Hard
ArrayBinary SearchQueueSliding WindowHeap (Priority Queue)Prefix SumMonotonic QueueSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a sliding window approach to maintain a dynamic range of robots. It keeps track of the maximum charge time and the sum of running costs efficiently, allowing us to check if the current window is within budget without recalculating everything.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize pointers for the sliding window and variables for the maximum charge time and total running cost.
  2. 2Step 2: Expand the right pointer to include more robots while checking if the total cost exceeds the budget.
  3. 3Step 3: If it exceeds, move the left pointer to reduce the window size until the cost is within budget.
  4. 4Step 4: Update the maximum length of the window whenever a valid configuration is found.
solution.py14 lines
1def maxRobots(chargeTimes, runningCosts, budget):
2    n = len(chargeTimes)
3    left = 0
4    total_running_cost = 0
5    max_charge = 0
6    max_length = 0
7    for right in range(n):
8        total_running_cost += runningCosts[right]
9        max_charge = max(max_charge, chargeTimes[right])
10        while max_charge + (right - left + 1) * total_running_cost > budget:
11            total_running_cost -= runningCosts[left]
12            left += 1
13        max_length = max(max_length, right - left + 1)
14    return max_length

Complexity note: This complexity is achieved because we only traverse the array once with two pointers, making it efficient.

  • 1The maximum charge time among selected robots significantly influences the total cost.
  • 2Using a sliding window allows for efficient management of the current set of robots being considered.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.