Medium
You are given a 2D integer array units of size m × n where units[i][j] represents the capacity of the jth unit in the ith 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):
i that has not been used as a source before.i and add it to any different device.i as 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:
Example 1:
Input: units = [[1,3],[2,2]]
Output: 4
Explanation:
i = 0 and transfer units[0][0] = 1 to device i = 1.0 = [3]: rating[0] = 31 = [2, 2, 1]: rating[1] = 13 + 1 = 4.Example 2:
Input: units = [[1,2,3],[4,5,6]]
Output: 6
Explanation:
i = 1 and transfer units[1][0] = 4 to device i = 0.0 = [1, 2, 3, 4]: rating[0] = 11 = [5, 6]: rating[1] = 51 + 5 = 6.Example 3:
Input: units = [[5,5,5],[1,1,1]]
Output: 6
Explanation:
5 + 1 = 6.Constraints:
1 <= m == units.length <= 1051 <= n == units[i].length <= 105m * n <= 2 * 1051 <= units[i][j] <= 105class Solution {
fun maxRatings(nums: Array<IntArray>): Long {
val n = nums[0].size
if (n == 1) {
var totalSum: Long = 0
for (num in nums) {
totalSum += num[0].toLong()
}
return totalSum
}
var sumM2: Long = 0
var min1Global = Int.MAX_VALUE
var min2Global = Int.MAX_VALUE
for (num in nums) {
var min1 = Int.MAX_VALUE
var min2 = Int.MAX_VALUE
for (j in 0..<n) {
val `val` = num[j]
if (`val` < min1) {
min2 = min1
min1 = `val`
} else if (`val` < min2) {
min2 = `val`
}
}
sumM2 += min2.toLong()
if (min1 < min1Global) {
min1Global = min1
}
if (min2 < min2Global) {
min2Global = min2
}
}
return min1Global + sumM2 - min2Global
}
}