dp
array of size books.length + 1
with dp[0] = 0
.1
to books.length
.i
, initialize width
as the thickness of the current book and height
as the height of the current book.dp[i]
to dp[i-1] + height
(placing the book on a new shelf).i-1
to 1
, and for each book j
, check if the sum of widths from j
to i
is less than or equal to shelfWidth
.height
to the maximum height of the books from j
to i
.dp[i]
to the minimum of its current value and dp[j-1] + height
(placing books j
to i
on the same shelf).dp
array, return dp[books.length]
as the answer.