leetcode: 1710. Maximum Units on a Truck

kldaji·2022년 7월 1일
0

leetcode

목록 보기
38/56

problem

sorting

class Solution {
    fun maximumUnits(boxTypes: Array<IntArray>, truckSize: Int): Int {
        // sort by unit in descending order
        boxTypes.sortBy { -it[1] }
        var mTruckSize = 0
        var answer = 0
        for (boxType in boxTypes) {
            mTruckSize += boxType[0]
            if (mTruckSize > truckSize) {
                // accumulate left units of boxes
                mTruckSize -= boxType[0]
                answer += (truckSize - mTruckSize) * boxType[1]
                break
            }
            // accumulate units of boxes
            answer += (boxType[0] * boxType[1])
        }
        return answer
    }
}
profile
다양한 관점에서 다양한 방법으로 문제 해결을 지향하는 안드로이드 개발자 입니다.

0개의 댓글