SWIFT: Efficient Shippling - Swift solution
func getMaxUnits(boxes :[Int], unitsPerBox: [Int], truckSize: Int) -> Int {
//invalid input
if boxes.count != unitsPerBox.count || truckSize <= 0 {
return 0
}
//struct to hold both values together
struct BoxAndUnits {
var box: Int
var units : Int
init(box: Int, units:Int) {
self.box = box
self.units = units
}
}
//attach boxes and units together for simple calculation
var arrBoxAndUnits = [BoxAndUnits]()
//Sort as per no of units
for n in 0..<boxes.count {
arrBoxAndUnits.append(BoxAndUnits.init(box: boxes[n], units: unitsPerBox[n]))
}
arrBoxAndUnits = arrBoxAndUnits.sorted(by: {$0.units > $1.units})
var productCount = 0
var boxesCollected = 0
for boxStruct in arrBoxAndUnits {
if (boxesCollected + boxStruct.box) >= truckSize {
let boxesToAdd = truckSize - boxesCollected
boxesCollected += boxesToAdd
productCount += boxesToAdd * boxStruct.units
break
} else {
boxesCollected += boxStruct.box
productCount += boxStruct.box * boxStruct.units
}
}
return productCount
}
Efficient Shippling - Swift solution |
Sign up here with your email
ConversionConversion EmoticonEmoticon