Skip to content

Commit 41a6841

Browse files
authored
Create 0983-minimum-cost-for-tickets.kt
1 parent 8faa8cd commit 41a6841

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: kotlin/0983-minimum-cost-for-tickets.kt

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* DP without a DFS
3+
*/
4+
class Solution {
5+
fun mincostTickets(days: IntArray, costs: IntArray): Int {
6+
val dp = IntArray(days.size) {-1}
7+
val zipped = intArrayOf(1,7,30).zip(costs)
8+
9+
for (i in days.lastIndex downTo 0) {
10+
dp[i] = Integer.MAX_VALUE
11+
for ((day, cost) in zipped) {
12+
var next = i
13+
while (next < days.size && days[next] < days[i] + day) next++
14+
dp[i] = minOf(
15+
dp[i],
16+
cost + if(next < days.size) dp[next] else 0
17+
)
18+
}
19+
}
20+
21+
return dp[0]
22+
}
23+
}
24+
25+
/*
26+
* DFS + cache
27+
*/
28+
class Solution {
29+
fun mincostTickets(days: IntArray, costs: IntArray): Int {
30+
val cache = IntArray(days.size) {-1}
31+
val zipped = intArrayOf(1,7,30).zip(costs)
32+
33+
fun dfs(i: Int): Int {
34+
if (i == days.size)
35+
return 0
36+
37+
if (cache[i] != -1)
38+
return cache[i]
39+
40+
cache[i] = Integer.MAX_VALUE
41+
for ((day, cost) in zipped) {
42+
var next = i
43+
while (next < days.size && days[next] < days[i] + day)
44+
next++
45+
cache[i] = minOf(cache[i], cost + dfs(next))
46+
}
47+
48+
return cache[i]
49+
}
50+
51+
return dfs(0)
52+
}
53+
}

0 commit comments

Comments
 (0)