JSFiddle - React, Tailwind, and code Playground

HTML

<div id="top"></div>
<div id="bottom"></div>

CSS

#top, #bottom {
    position: absolute;
    left: 0;
    right: 0;
    overflow: auto;    
}

#top { 
    top: 0;  
    bottom: 50%;
    border-bottom: 1px solid black;
}

#bottom {
    top: 50%;
    bottom: 0;
    border-top: 1px solid black;
}

JavaScript

function minBoxes(boxes) {
    boxes = boxes.sort(function(box1, box2) {
        return box1.z - box2.z;
    }).map(function(box1) {
        var overlapping = {};
        boxes.forEach(function(box2) {
            if(box1 != box2
                && box1.x + box1.w > box2.x
                && box2.x + box2.w > box1.x
                && box1.y + box1.h > box2.y
                && box2.y + box2.h > box1.y
            ) {
                overlapping[box2.z] = true;
            }
        });
        return {
            x: box1.x,
            y: box1.y,
            w: box1.w,
            h: box1.h,
            minZ: box1.z,
            maxZ: box1.z,
            overlapping: overlapping
        };
    });

    var result = [];

    boxes.forEach(function(box1) {
        var bestBox,
            bestIndex;

        function combinedBox(box2) {
            var x = Math.min(box1.x, box2.x),
                y = Math.min(box1.y, box2.y);
            return {
                x: x,
                y: y,
                w: Math.max(box1.x + box1.w, box2.x + box2.w) - x,
                h: Math.max(box1.y + box1.h, box2.y + box2.h) - y
            };
        }
        result.reduce(function(bestSavings, box2, i) {
            //check z-order
            var min = Math.max(Math.min(box1.minZ, box2.maxZ), Math.min(box1.maxZ, box2.minZ)),
                max = Math.min(Math.max(box1.minZ, box2.maxZ), Math.max(box1.maxZ, box2.minZ));
            for(var z in box1.overlapping) {
                if(min < z && z < max && z in box2.overlapping) {
                    return bestSavings;
                }
            }
            for(var z in box2.overlapping) {
                if(min < z && z < max && z in box1.overlapping) {
                    return bestSavings;
                }
            }
            //check area savings
            var combined = combinedBox(box2);
            var savings = box1.w * box1.h + box2.w * box2.h - combined.w * combined.h;
            if(savings >...