# Code language: Python classSolution: defmaximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: boxTypes.sort(key=lambda x: x[1], reverse=True) ans = 0 for i, j in boxTypes: ans += min(i, truckSize) * j truckSize -= i if truckSize <= 0: break return ans
1 2 3 4 5 6 7 8 9 10 11 12
// Code language: Java classSolution { publicintmaximumUnits(int[][] boxTypes, int truckSize) { Arrays.sort(boxTypes, (a,b)->b[1]-a[1]); intans=0; for (inti=0, n = boxTypes.length; i < n && truckSize > 0; ++i) { ans += Math.min(boxTypes[i][0], truckSize) * boxTypes[i][1]; truckSize -= boxTypes[i][0]; } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13
// Code language: C++ classSolution { public: intmaximumUnits(vector<vector<int>>& boxTypes, int truckSize){ sort(boxTypes.begin(), boxTypes.end(), [](vector<int>& a, vector<int>& b){return a[1] >= b[1];}); int ans = 0; for (int i = 0, n = boxTypes.size(); i < n && truckSize > 0; i++) { ans += min(boxTypes[i][0], truckSize) * boxTypes[i][1]; truckSize -= boxTypes[i][0]; } return ans; } };
时间复杂度: \(O(n \log n)\)
空间复杂度: \(O(\log n)\),
视排序算法而定
计数排序
1 2 3 4 5 6 7 8 9 10 11 12
# Code language: Python classSolution: defmaximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: s = [0] * 1007 for i, j in boxTypes: s[j] += i ans = 0 for i, j inzip(count(1006, -1), reversed(s)): if j > 0: ans += min(j, truckSize) * i truckSize -= j if truckSize <= 0: break return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Code language: Java classSolution { publicintmaximumUnits(int[][] boxTypes, int truckSize) { int[] s = newint[1007]; intans=0; for (inti=0, n = boxTypes.length; i < n; ++i) s[boxTypes[i][1]] += boxTypes[i][0]; for (inti=1000; i > 0 && truckSize > 0; i--) { if (s[i] > 0) { ans += Math.min(s[i], truckSize) * i; truckSize -= s[i]; } } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: intmaximumUnits(vector<vector<int>>& boxTypes, int truckSize){ int s[1007]{0}; int ans = 0; for (int i = 0, n = boxTypes.size(); i < n; ++i) s[boxTypes[i][1]] += boxTypes[i][0]; for (int i = 1000; i > 0 && truckSize > 0; i--) { if (s[i] > 0) { ans += min(s[i], truckSize) * i; truckSize -= s[i]; } } return ans; } };