Posts

Showing posts with the label Deque

Maximum Number of Tasks You Can Assign - Binary Search & Deque [JS]

Description   Solution: Binary Search & Deque Binary search for the largest number of tasks that can be completed. How to check whether we can complete k tasks: Try to assign the k weakest tasks to the k strongest workers. Sort tasks in asc order and workers in desc order. Go through the workers from weakest to strongest, Try to assign the easiest task to the worker (without using a pill). If it can be assigned, assign it. (If the easiest task can be done by the worker, that means all following workers will be able to do it without a pill. Therefore, it is optimal for the current task to complete the easiest task) Otherwise, try to do the hardest possible task after using a pill. Keep track of the tasks that are assignable after using a pill in a deque so that we can remove tasks both on the left and right. If we can't assign any task to the worker, return false (we can't complete k tasks). n = number of tasks ,  m = number of workers Time Complexity:  O(n log(n) + m ...

Maximum Number of Robots Within Budget - Sliding Window & Monotonic Decreasing Deque [JS]

Description   Solution: Sliding Window & Monotonic Decreasing Deque Maintain a sliding window where the  total cost <= budget . When the total cost exceeds the budget, move up the left pointer until it is within the budget. To get the maximum chargeTime so far, maintain a monotonic decreasing queue. There is no point keeping smaller chargeTimes at earlier indexes. Remove smaller chargeTimes from the back of the queue. As we move the left pointer up, remove expired indexes from the front of the queue. The chargeTime at the front of the queue is the maximum chargeTime in the current window. Record the largest size of the sliding window. Time Complexity:  O(n)  276ms Space Complexity:  O(n)  58.9MB var maximumRobots = function(chargeTimes, runningCosts, budget) { let n = chargeTimes.length, queue = new Deque(); let runningCost = 0 , ans = 0 ; for (let j = 0 , i = 0 ; j < n; j++) { runningCost += runningCosts[j]; while (!queue.isEmpty...