Online store~30 min2s · 256 MBtarget O(total × 4^n) at worst, cut by sorting and skipping equal sides time, O(n) spaceclassic twin: lc-473backtracking
An online store sells custom picture frames. A frame is a rectangle with four sides. Each side is made by joining whole wood strips end to end, and strips can not be cut.
A customer sends all the strips they have. Every strip must be used. The two long sides must have the same length, and so must the two short sides. The store wants the frame with the largest inner area.
Write best_frame_area(strips).
strips is a list of whole numbers, the lengths of the strips.-1 when no frame can be made.Input: strips = [6,4,3,3,2,2]
Output: 24The total is 20, so the width and the height add up to 10. The solution tries the width from the widest, which is 5, downwards. A width is tested by placing the strips, longest first, on the four sides.
| Width | Height | Result |
|---|---|---|
| 5 | 5 | the strip 6 is longer than every side, so it fails at once |
| 4 | 6 | sides 4, 4, 6, 6: the strips go as 4, 2 + 2, 6, 3 + 3 |
The first width that works is 4, so the area is 4 × 6 = 24.
Input: strips = [1,1,2,2]
Output: 2The width 1 and the height 2 use every strip. A frame needs at least four strips.
Input: strips = [2,2,2]
Output: -1The total 6 is even, but three strips can not fill four sides.
1 ≤ len(strips) ≤ 141 ≤ strips[i] ≤ 30Giving each strip one of four sides makes 4^14 ways, which is 268,435,456. Testing each of them is slow, but a search that stops as soon as a side overflows visits far fewer. Sorting the strips from the longest makes the overflow show up early.