본문 바로가기

Java/Java 알고리즘 LeetCode

[LeetCode- Part. 2] 2. 트럭의 실을 수 있는 최대단위

반응형

https://leetcode.com/problems/maximum-units-on-a-truck/

 

Maximum Units on a Truck - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

트럭 한 대에 상자를 넣는 2차원 배열

boxTypes[i] = [numberOfBoxes, numberOfUnitsPerBox]

 

트럭에 실을 수 있는 상자 truckSize가 주어지면
truckSize
를 초과하지 않는 한 트럭에 넣을 상자를 선택해, 트럭에 실을 수있는 최대 총 단위 수를 반환

 

문제 풀이 순서

1. 유닛 개수 내림차순, 박스 수 오름차순 정렬

2. 존재하는 박스 개수만큼 담고, 만약 필요한 트럭개수보다 박스개수가 많은 경우, 남은 트럭 사이즈만큼 박스 추가

 

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        //박스 [[1박스 ,3개 유닛],[2박스,2개 유닛],[3박스,1개 유닛]]
        int answer=0;int n=boxTypes.length;
        Arrays.sort(boxTypes, (o1,o2) -> o1[1]==o2[1]? o1[0]-o2[0]:o2[1]-o1[1]);
        // for(int i=0;i<n;i++){
        //     for(int j=0;j<boxTypes[0].length;j++){
        //         System.out.print(boxTypes[i][j]+" ");
        //     }
        //     System.out.println();
        // }
        for(int i=0;i<n;i++){
            if(truckSize>=boxTypes[i][0]){
              truckSize-=boxTypes[i][0];
                answer+=boxTypes[i][0]*boxTypes[i][1];
                System.out.println(i+" "+boxTypes[i][0]);
            } 
            else {
                answer+=boxTypes[i][1]*truckSize;
                break;
            }
        }
        return answer;
    }
}

+) 세련된 코드

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        //박스 [[1박스 ,3개 유닛],[2박스,2개 유닛],[3박스,1개 유닛]]
		Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
		int unitCount = 0;
		for (int[] boxType : boxTypes) {
			int boxCount = Math.min(truckSize, boxType[0]);
			unitCount += boxCount * boxType[1];
			truckSize -= boxCount;
			if (truckSize == 0)
				break;
		}
		return unitCount;
	}
반응형