-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0983-minimum-cost-for-tickets.kt
51 lines (39 loc) · 1.36 KB
/
0983-minimum-cost-for-tickets.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* DFS solution
*/
class Solution {
fun mincostTicketsRecursive(days: IntArray, costs: IntArray): Int {
val dp = mutableMapOf<Int, Int>()
fun dfs(dayIndex: Int): Int {
if (dayIndex == days.size) return 0
if (dayIndex in dp) return dp[dayIndex]!!
dp[dayIndex] = Int.MAX_VALUE
for ((daysCount, cost) in intArrayOf(1, 7, 30).zip(costs)) {
var nextDayIndex = dayIndex
while (nextDayIndex < days.size && days[nextDayIndex] < days[dayIndex] + daysCount)
nextDayIndex++
dp[dayIndex] = min(dp[dayIndex]!!, cost + dfs(nextDayIndex))
}
return dp[dayIndex]!!
}
return dfs(0)
}
}
/*
* BFS Solution
*/
class Solution {
fun mincostTickets(days: IntArray, costs: IntArray): Int {
val dp = mutableMapOf<Int, Int>()
for (dayIndex in days.indices.reversed()) {
dp[dayIndex] = Int.MAX_VALUE
for ((daysCount, cost) in intArrayOf(1, 7, 30).zip(costs)) {
var nextDayIndex = dayIndex
while (nextDayIndex < days.size && days[nextDayIndex] < days[dayIndex] + daysCount)
nextDayIndex++
dp[dayIndex] = min(dp[dayIndex]!!, cost + dp.getOrDefault(nextDayIndex, 0))
}
}
return dp[0]!!
}
}