1
- # Runtime: 88 ms (Top 43.53%) | Memory: 15.4 MB (Top 42.69%)
2
-
3
1
class Solution :
4
- def recursion (self , idx , n , height , width ):
5
- if idx == n :return height
6
-
7
- if (idx ,height ,width ) in self .dp : return self .dp [(idx ,height ,width )]
8
-
9
- choice1 = self .recursion (idx + 1 ,n ,max (self .books [idx ][1 ],height ), width - self .books [idx ][0 ])\
10
- if width >= self .books [idx ][0 ] else float ('inf' )
2
+ def minHeightShelves (self , books , shelf_width : int ) -> int :
3
+ n , dp = len (books ), [float ('inf' )] * (len (books )+ 1 )
4
+ dp [0 ] = 0
11
5
12
- choice2 = self .recursion (idx + 1 ,n ,self .books [idx ][1 ], self .shelfWidth - self .books [idx ][0 ]) + height
6
+ for i in range (1 , n + 1 ):
7
+ max_width , max_height , j = shelf_width , 0 , i - 1
8
+
9
+ while j >= 0 and max_width - books [j ][0 ] >= 0 :
10
+ max_width -= books [j ][0 ]
11
+ max_height = max (max_height , books [j ][1 ])
12
+ dp [i ] = max_height
13
+ j -= 1
13
14
14
- ans = min (choice1 ,choice2 )
15
- self .dp [(idx ,height ,width )] = ans
16
- return ans
15
+ if j >= 0 and max_width - books [j ][0 ] < 0 :
16
+ j = i - 1
17
+ dp [i ] = float ('inf' )
18
+ width , height = 0 , 0
19
+ while j >= 0 and width + books [j ][0 ] <= shelf_width :
20
+ width = width + books [j ][0 ]
21
+ height = max (books [j ][1 ], height )
22
+ dp [i ] = min (dp [i ], height + dp [j ])
23
+ j -= 1
17
24
18
- def minHeightShelves (self , books : List [List [int ]], shelfWidth : int ) -> int :
19
- self .books = books
20
- self .shelfWidth = shelfWidth
21
- self .dp = {}
22
- return self .recursion (0 ,len (books ),0 ,shelfWidth )
25
+ return dp [n ]
0 commit comments