Maximum Number of Tasks You Can Assign — LeetCode 2071 Python Solution
HardGreedyQueueArrayTwo PointersBinary SearchSortingMonotonic Queue
- Problem
- #2071
- Pattern
- Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete.
Example
- Input
- tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1
- Output
- 3
- Explanation
- We can assign the magical pill and tasks as follows:
Python solution
Python
class Solution:
def maxTaskAssign(
self, tasks: List[int], workers: List[int], pills: int, strength: int
) -> int:
def check(x):
i = 0
q = deque()
p = pills
for j in range(m - x, m):
while i < x and tasks[i] <= workers[j] + strength:
q.append(tasks[i])
i += 1
if not q:
return False
if q[0] <= workers[j]:
q.popleft()
elif p == 0:
return False
else:
p -= 1
q.pop()
return True
n, m = len(tasks), len(workers)
tasks.sort()
workers.sort()
left, right = 0, min(n, m)
while left < right:
mid = (left + right + 1) >> 1
if check(mid):
left = mid
else:
right = mid - 1
return leftComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n), where n is the number of tasks auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2071. Maximum Number of Tasks You Can Assign is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2071. Maximum Number of Tasks You Can Assign?
- LeetCode 2071. Maximum Number of Tasks You Can Assign is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2071. Maximum Number of Tasks You Can Assign?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2071. Maximum Number of Tasks You Can Assign?
- The Python solution on this page uses O(n), where n is the number of tasks auxiliary space.
- What topics does LeetCode 2071. Maximum Number of Tasks You Can Assign cover?
- LeetCode 2071. Maximum Number of Tasks You Can Assign is tagged Greedy, Queue, Array, Two Pointers, Binary Search, Sorting and Monotonic Queue on LeetCode.