Skip to content

Commit 6c2dd14

Browse files
authored
Create 1547-minimum-cost-to-cut-a-stick.kt
1 parent 518d495 commit 6c2dd14

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
fun minCost(n: Int, c: IntArray): Int {
3+
val cuts = c.toCollection(ArrayList()).apply {
4+
add(0)
5+
add(n)
6+
sort()
7+
}
8+
9+
val dp = Array (cuts.size) { IntArray (cuts.size) { -1 } }
10+
11+
fun dfs(l: Int, r: Int): Int {
12+
if (r - l <= 1)
13+
return 0
14+
if (dp[l][r] == -1) {
15+
dp[l][r] = Integer.MAX_VALUE
16+
for (c in l + 1 until r) {
17+
dp[l][r] = minOf(
18+
dp[l][r],
19+
dfs(l, c) + dfs(c, r) + (cuts[r] - cuts[l])
20+
)
21+
}
22+
}
23+
24+
return dp[l][r]
25+
}
26+
27+
return dfs(0, cuts.lastIndex)
28+
}
29+
}

0 commit comments

Comments
 (0)