Last active
May 3, 2017 13:53
-
-
Save dimonomid/77afcceaf229d161abc7196e2daeb1f1 to your computer and use it in GitHub Desktop.
Get required cars number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getRequiredCarsNum2(busCap, carCap int, stations []int) int { | |
cars := 0 | |
busUsed := false | |
resortFullBus := -1 | |
resortHalfBus := -1 | |
halfBusMax := 0 | |
for i, p := range stations { | |
// Don't care about empty stations | |
if p == 0 { | |
continue | |
} | |
// If we didn't use the bus yet, consider it | |
if !busUsed { | |
if p >= busCap { | |
if (p-busCap)%carCap == 0 { | |
// This station is a great fit for the bus, so, use it | |
p -= busCap | |
busUsed = true | |
} else if resortFullBus == -1 && p%carCap != 0 { | |
// Remember the first station which is not a great fit for cars only: | |
// if there's no perfect fit for the bus, we'll resort to that | |
resortFullBus = i | |
} | |
} | |
if p > halfBusMax { | |
// Also remember the last last resort, for which the bus won't be full, | |
// but at least it will carry maximum number of passengers | |
halfBusMax = p | |
resortHalfBus = i | |
} | |
} | |
cars += getCarsCnt(p, carCap) | |
} | |
// If we haven't used the bus (because there was no perfect fit for it), use | |
// resortFullBus | |
if len(stations) > 0 && !busUsed { | |
// First, try to resort to some station which would fill the bus fully | |
resort := resortFullBus | |
// If it wasn't successful, resort to half-filled bus | |
if resort == -1 { | |
resort = resortHalfBus | |
} | |
// If that is not successful either, it doesn't matter where to send the bus, | |
// just pick the first station | |
if resort == -1 { | |
resort = 0 | |
} | |
// Fixup cars number by reconsidering the bus for resort | |
p := stations[resort] | |
cars -= getCarsCnt(p, carCap) | |
p -= busCap | |
if p < 0 { | |
p = 0 | |
} | |
cars += getCarsCnt(p, carCap) | |
} | |
return cars | |
} | |
func getCarsCnt(passengers, carCap int) int { | |
return (passengers + (carCap - 1)) / carCap | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment