![]() |
VOOZH | about |
Given two machines, Machine A and Machine B, and a set of n tasks. The profit earned for performing each task is given in two arrays a[] and b[] such that if Machine A performs the i-th task, the profit is a[i], and if Machine B performs it, the profit is b[i].
Machine A can process at most x tasks, and Machine B can process at most y tasks. It is guaranteed that x + y β₯ n, so all tasks can be assigned. Return the maximum possible profit after assigning each task to either Machine A or Machine B.
Examples:
Input: x = 3, y = 3, a[] = {1, 2, 3, 4, 5}, b[] = {5, 4, 3, 2, 1}
Output: 21
Explanation: Machine A will process the 3, 4 and 5 tasks while Machine B will process the rest so the total profit from A = 3 + 4 + 5 and B = 5 + 4 i.e. 21.Input: x = 3, y = 4, a[] = {8, 7, 15, 19, 16, 16, 18}, b[] = {1, 7, 15, 11, 12, 31, 9}
Output: 110
Explanation: Machine A will process tasks 8, 19, 18 while Machine B will process tasks 7, 15, 12 and 31.
Table of Content
The simplest approach is to use recursion because for each task, we have two choices: assign it to Machine A or Machine B. We recursively try both options and pick the one that maximizes the total profit, while ensuring that neither A nor B exceeds their order limits. As in every step, there is a choice to be made, this is similar to the 0-1 Knapsack Problem, in which decisions are made whether to include or exclude an element.
Below is the implementation of the above approach:
21
The above approach can be optimized by using Dynamic Programming and Memoization. The recursive solution has overlapping subproblems because the same state (i, x, y) is computed multiple times. We can store the result of each state in a DP table and reuse it, reducing time complexity from exponential to polynomial.
Below is the implementation of the above approach:
21
The idea is that we should first handle the tasks where the difference between profits is highest, because choosing the wrong machine for those tasks would cause the biggest loss. For tasks where both machines give similar profits, it doesnβt matter much who processes them. So, we greedily assign each task to the machine who gives higher profit while respecting constraints.
Dry run for the above example: a = {1, 2, 3}, b = {5, 4, 2}, x = 2, y = 1
Final answer: maximum profit = 10
21