Created
December 5, 2018 18:10
-
-
Save mrnkr/2af545a3786cbf766b9af6f47b38dd15 to your computer and use it in GitHub Desktop.
Dynamic Programming exercise - Help someone on the run from the cops to get to the border stopping in as few gas stations as possible. When you stop at one you drop all your gas cause your car is a bit messed up :P
This file contains hidden or 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
import Foundation | |
func min(array: [Int]) -> Int { | |
var ret = Int.max; | |
for i in 0...array.count - 1 { | |
if array[i] < ret { | |
ret = array[i] | |
} | |
} | |
return ret | |
} | |
func ayudameNey(estaciones: [Int]) -> [Int] { | |
var paradas: [Int] = Array.init(repeating: 0, count: estaciones.count) | |
for i in stride(from: paradas.count - 2, to: -1, by: -1) { | |
if i + estaciones[i] >= paradas.count - 1 { | |
paradas[i] = 1 | |
continue | |
} | |
paradas[i] = 1 + min(array: Array(Array(paradas.suffix(from: i + 1)).prefix(upTo: estaciones[i]))) | |
} | |
var cnt: Int = 0 | |
var ret: [Int] = Array(repeating: 0, count: paradas[0] + 1) | |
for i in stride(from: paradas[0], to: -1, by: -1) { | |
ret[cnt] = paradas.firstIndex(of: i) ?? 0 | |
cnt = cnt + 1 | |
} | |
return ret; | |
} | |
let res = ayudameNey(estaciones: [1,3,5,2,1,1,6,7,1,3,9]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment