Maximize Sum of Device Ratings Problem
Description
LeetCode Problem 3961.
You are given a 2D integer array units of size m × n where units[i][j] represents the capacity of the j^th unit in the i^th device. Each device contains exactly n units.
The rating of a device is the minimum capacity among all its units.
You may perform the following operation any number of times (including zero):
- Choose a device
ithat has not been used as a source before. - Remove exactly one unit from device
iand add it to any different device. - Then mark device
ias used, so it cannot be chosen again as a source.
Return the maximum possible sum of the ratings of all devices after any number of such operations.
Note:
- Devices can receive units from multiple devices, regardless of whether they have been selected.
- The rating of an empty device is 0.
Example 1:
Input: units = [[1,3],[2,2]]
Output: 4
Explanation:
- Select device i = 0 and transfer units[0][0] = 1 to device i = 1.
- After the transfer, the ratings are:
- Device 0 = [3]: rating[0] = 3
- Device 1 = [2, 2, 1]: rating[1] = 1
- Thus, the sum of ratings is 3 + 1 = 4.
Example 2:
Input: units = [[1,2,3],[4,5,6]]
Output: 6
Explanation:
- Select device i = 1 and transfer units[1][0] = 4 to device i = 0.
- After the transfer, the ratings are:
- Device 0 = [1, 2, 3, 4]: rating[0] = 1
- Device 1 = [5, 6]: rating[1] = 5
- Thus, the sum of ratings is 1 + 5 = 6.
Example 3:
Input: units = [[5,5,5],[1,1,1]]
Output: 6
Explanation:
- No transfers increase the sum of ratings. Thus, the sum of ratings is 5 + 1 = 6.
Constraints:
1 <= m == units.length <= 10^51 <= n == units[i].length <= 10^5m * n <= 2 * 10^51 <= units[i][j] <= 10^5
Solution
Approach: Greedy
Adding a unit to a device can never raise its rating. If every device has a single unit (n = 1), nothing useful can be moved (a device that gives its only unit away is left empty with rating 0), so the answer is the sum of the ratings.
Otherwise, a device that gives away its smallest unit has its rating rise to its second smallest unit, so we want as many devices as possible to do that. All the removed units must land somewhere, and the best place is a single receiving device i that does not give anything away: its rating becomes the global minimum mn, whichever device that comes from. Compared with the sum of every device's second smallest value, the receiver i costs second_i - mn, so pick the receiver with the smallest second smallest value mn2.
Sort each device (or just find its two smallest units) and return sum(second smallest) - (mn2 - mn).
Complexity: time O(m * n log n) with sorting (O(m * n) if only the two smallest are tracked), space O(1) extra.
class Solution:
def maxRatings(self, units: List[List[int]]) -> int:
n = len(units[0])
if n == 1:
return sum(x[0] for x in units)
ans = 0
mn = mn2 = float("inf")
for x in units:
x.sort()
ans += x[1]
mn2 = min(mn2, x[1])
mn = min(mn, x[0])
ans -= mn2 - mn
return ans