Sponsored
This approach involves sorting the box types by the number of units per box in descending order. Once sorted, the boxes are loaded onto the truck with the highest units per box first, maximizing the number of units on the truck until it reaches its capacity.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) extra space, as we sort in place.
1using System;
2
3public class Solution {
4 public int MaximumUnits(int[][] boxTypes, int truckSize) {
5 Array.Sort(boxTypes, (a, b) => b[1] - a[1]);
6 int totalUnits = 0;
7 foreach (var box in boxTypes) {
8 int boxesToTake = Math.Min(box[0], truckSize);
9 totalUnits += boxesToTake * box[1];
10 truckSize -= boxesToTake;
11 if (truckSize == 0) break;
12 }
13 return totalUnits;
14 }
15}
The C# solution sorts the array based on descending units and iteratively selects box types for the maximum unit count.
Instead of sorting by each unit's count, employ counting sort principles to store the total units in an array where the index represents the units per box. This could potentially be faster for large inputs with many boxes and limited unit types.
Time Complexity: O(n + M) where M = 1000 is a constant.
Space Complexity: O(M) for the counting array.
1
This approach uses a counting array where the index represents units per box to aggregate total boxes available. The truck is filled according to the highest units available in the count array.