g1101_1200.s1105_filling_bookcase_shelves.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g1101_1200.s1105_filling_bookcase_shelves
// #Medium #Array #Dynamic_Programming #2023_05_31_Time_175_ms_(33.33%)_Space_39.8_MB_(33.33%)
class Solution {
fun minHeightShelves(books: Array, shelfWidth: Int): Int {
val n = books.size
val dp = IntArray(n + 1)
dp.fill(Int.MAX_VALUE)
dp[0] = 0
for (i in 1..n) {
var widthLeft = shelfWidth
var maxH = 0
for (j in i - 1 downTo 0) {
widthLeft -= books[j][0]
maxH = Math.max(maxH, books[j][1])
if (widthLeft >= 0) {
dp[i] = Math.min(dp[i], maxH + dp[j])
}
}
}
return dp[n]
}
}