You are assigned to put some amount of boxes onto one truck. You are given a 2D array
boxTypes
, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]
:numberOfBoxesi
is the number of boxes of typei
.
numberOfUnitsPerBoxi
is the number of units in each box of the typei
.
truckSize
, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize
.Example 1:
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Approach
Java
import java.util.Arrays;import java.util.Comparator;public class MaximumUnitsTruck {public static void main(String[] args) {int[][] boxTypes = { { 1, 3 }, { 2, 2 }, { 3, 1 } };int truckSize = 4;System.out.println(maximumUnits(boxTypes, truckSize));}// function to find the maximum units// on the truckstatic int maximumUnits(int[][] boxTypes, int truckSize) {// sort the boxtypesArrays.sort(boxTypes, Comparator.comparingDouble(o -> o[1]));int ans = 0;for (int i = boxTypes.length - 1; i >= 0; i--) {// if truckSize is less than bixTypes// then update answer and breakif (truckSize <= boxTypes[i][0]) {ans = ans + truckSize * boxTypes[i][1];break;}// else update answer and// decrease the trucksizeelse {ans = ans + boxTypes[i][0] * boxTypes[i][1];truckSize -= boxTypes[i][0];}}// return the final answerreturn ans;}}C++
#include <bits/stdc++.h>using namespace std;//compartor to sort the array//in which order we wnad to sort the arraystatic bool cmp(vector<int> a,vector<int> b){if(a[1]==b[1])return a[0]>b[0];return a[1]>b[1];}//function to find the maximum units//on the truckint maximumUnits(vector<vector<int>>& boxTypes, int truckSize){// sort the boxtypessort(boxTypes.begin(),boxTypes.end(),cmp);int ans=0;for(int i=0;i<boxTypes.size();i++){//if truckSize is less than bixTypes//then update answer and breakif(truckSize<=boxTypes[i][0]){ans=ans+truckSize*boxTypes[i][1];break;}//else update answer and//decrease the trucksizeelse{ans=ans+boxTypes[i][0]*boxTypes[i][1];truckSize-=boxTypes[i][0];}}//return the final answerreturn ans;}int main(){vector<vector<int>> boxTypes ={{1,3},{2,2},{3,1}};int truckSize = 4;cout<<maximumUnits(boxTypes,truckSize);return 0;}
No comments:
Post a Comment