Box Stacking | Practice | GeeksforGeeks

You are given a set of N types of rectangular 3-D boxes, where the ith box has height h, width w and length l. You task is to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base.It is also allowable to use multiple instances of the same type of box. You task is to complete the function maxHeight which returns the height of the highest possible stack so formed.
 
Note: 
Base of the lower box should be strictly larger than that of the new box we're going to place. This is in terms of both length and width, not just in terms of area. So, two boxes with same base cannot be placed one over the other.
 
Example 1:
Input:
n = 4
height[] = {4,1,4,10}
width[] = {6,2,5,12}
length[] = {7,3,6,32}
Output: 60
Explanation: One way of placing the boxes is
as follows in the bottom to top manner:
(Denoting the boxes in (l, w, h) manner)
(12, 32, 10) (10, 12, 32) (6, 7, 4) 
(5, 6, 4) (4, 5, 6) (2, 3, 1) (1, 2, 3)
Hence, the total height of this stack is
10 + 32 + 4 + 4 + 6 + 1 + 3 = 60.
No other combination of boxes produces a
height greater than this.

Example 2:
Input:
n = 3
height[] = {1,4,3}
width[] = {2,5,4}
length[] = {3,6,1}
Output: 15
Explanation: One way of placing the boxes is
as follows in the bottom to top manner:
(Denoting the boxes in (l, w, h) manner)
(5, 6, 4) (4, 5, 6) (3, 4, 1), (2, 3, 1) 
(1, 2, 3).
Hence, the total height of this stack is
4 + 6 + 1 + 1 + 3 = 15
No other combination of boxes produces a
height greater than this.

Your Task:
You don't need to read input or print anything. Your task is to complete the function maxHeight() which takes three arrays height[], width[], length[], and N as a number of boxes and returns the highest possible stack height which could be formed.

Expected Time Complexity : O(N*N)
Expected Auxiliary Space: O(N)

Constraints:
1<= N <=100
1<= l,w,h <=100
0
nrkarlapati1 week ago
Very efficient O(n^2) solution, runs in 0.27 s/15s
 
// { Driver Code Starts//Initial Template for Java
import java.util.*;import java.lang.*;import java.io.*;class GFG{   public static void main(String[] args) throws IOException   {       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));       int T = Integer.parseInt(br.readLine().trim());       while(T-->0)       {           int n = Integer.parseInt(br.readLine().trim());           String[] s1 = br.readLine().trim().split(" ");           int[] height = new int[n];           for(int i = 0; i < n; i++){               height[i] = Integer.parseInt(s1[i]);           }           String[] s2 = br.readLine().trim().split(" ");           int[] width = new int[n];           for(int i = 0; i < n; i++){               width[i] = Integer.parseInt(s2[i]);           }           String[] s3 = br.readLine().trim().split(" ");           int[] length = new int[n];           for(int i = 0; i < n; i++){               length[i] = Integer.parseInt(s3[i]);           }           Solution obj = new Solution();           System.out.println(obj.maxHeight(height, width, length, n));       }   }}// } Driver Code Ends
//User function Template for Java
class Solution{   public static int maxHeight(int[] height, int[] width, int[] length, int n)   {       // Code here                     //width > length       Box[] boxes = new Box[3*n];             for(int i=0;i<n;i++){           int w = Math.max(width[i],length[i]);           int l = Math.min(width[i],length[i]);           boxes[3*i] = new Box(w,l,height[i]);                      w = Math.max(width[i],height[i]);           l = Math.min(width[i],height[i]);           boxes[3*i+1] = new Box(w,l,length[i]);                      w = Math.max(height[i],length[i]);           l = Math.min(height[i],length[i]);           boxes[3*i+2] = new Box(w,l,width[i]);                  }              Arrays.sort(boxes);       int[] msh = new int[3*n];       msh[0] = boxes[0].height;       for(int i=1;i<3*n;i++){           msh[i] = boxes[i].height;//Integer.MIN_VALUE;           for(int j=0;j<i;j++){               if(boxes[i].width < boxes[j].width && boxes[i].length < boxes[j].length){                   msh[i] = Math.max(msh[i] , msh[j]+boxes[i].height);               }           }       }       int output = Integer.MIN_VALUE;       for(int i=0;i<3*n;i++){           output = Math.max(output,msh[i] );       }              // Stream.of(boxes).reduce(Math::max);       return output;          }      static class Box implements Comparable<Box>{       int width;       int length;       int height;       Box(int width, int length, int height){           this.width = width;           this.length = length;           this.height = height;       }       @Override       public int compareTo(Box other){           return other.width * other.length - width * length;       }                 }}
0
hamidnourashraf1 month ago
class Solution:
    def maxHeight(self, h, w, l, n):
        rotations = []
        for i in range(n):
            rot = [0]*3
            _w = w[i]
            _l = l[i]
            _h = h[i]
            rot[2] = _w
            rot[1] = min(_l, _h)
            rot[0] = max(_l, _h)
            rotations.append(rot)
            rot = [0]*3
            rot[2] = _h
            rot[1] = min(_l, _w)
            rot[0] = max(_l, _w)
            rotations.append(rot)
            rot = [0]*3
            rot[2] = _l
            rot[1] = min(_h, _w)
            rot[0] = max(_h, _w)
            rotations.append(rot)
        rotations.sort(reverse=True, key=lambda X: X[0]*X[1])
        n = n*3
        mh = [0]* n
        for i in range(n):
            mh[i] = rotations[i][2]
        
        for i in range(1, n):
            for j in range(0, i):
                if rotations[i][0] < rotations[j][0] and rotations[i][1] < rotations[j][1]:
                    if mh[i] < mh[j] +  rotations[i][2]:
                        mh[i] = mh[j] +  rotations[i][2]
                        
        return max(mh)
+1
kuldeepy104591 month ago
public:   /*The function takes an array of heights, width and    length as its 3 arguments where each index i value    determines the height, width, length of the ith box.    Here n is the total no of boxes.*/       struct box{   int l,r,h;   void setBox(int a,int b,int c){       l=a;       r=b;       h=c;   }   };//   bool cmp(box &a, box& b){//         return (a.l*a.r)<(b.l*b.r);//     }   int maxHeight(int h[],int w[],int l[],int n)   {       //Your code here       box b[3*n];int j=0;       for(int i=0;i<n;i++){           b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]);           b[j++].setBox(min(l[i],w[i]),max(l[i],w[i]),h[i]);           b[j++].setBox(min(h[i],l[i]),max(h[i],l[i]),w[i]);       }       n=n*3;       sort(b,b+n,[&](box &a,const box&b){  return (a.l*a.r)>(b.l*b.r);});             int res[n];       for(int i=0;i<n;i++){           res[i]=b[i].h;       }              for(int i=1;i<n;i++){           for(int j=i-1;j>=0;j--){               if(b[i].l<b[j].l&&b[i].r<b[j].r&&res[i] < res[j] + b[i].h){                   res[i]= res[j]+b[i].h;                                  }                          }       }       int mx = -1;      for(int i=0;i<n;i++){       mx=max(mx,res[i]);        }  return mx;
   }
0
geminicode2 months ago
Must be in Hard !! here is my python solution.
def maxHeight(self,height, width, length, n):
        #Code here
        
        arr = [[0,0,0] for i in range(3*n)]
        index = 0
        #generate all 3*n combinations
        for i in range(n):
            arr[index][0] = height[i]
            arr[index][1] = max(width[i],length[i])
            arr[index][2] = min(width[i],length[i])
            index+=1
            
            arr[index][0] = width[i]
            arr[index][1] = max(length[i],height[i])
            arr[index][2] = min(length[i],height[i])
            index+=1
            arr[index][0] = length[i]
            arr[index][1] = max(width[i],height[i])
            arr[index][2] = min(width[i],height[i])
            index+=1
        arr.sort(key = lambda x:x[1]*x[2],reverse = True)
        #print(arr)
        dp = [0 for i in range(3*n)]
        for i in range(3*n):
            dp[i] = arr[i][0]
        #print(dp)
        #print(arr)
        for i in range(1,3*n):
            for j in range(i):
                if arr[i][1] < arr[j][1] and arr[i][2] < arr[j][2] and \
                dp[j]+arr[i][0] > dp[i]:
                    dp[i] = dp[j] + arr[i][0]
        #print(dp)
        return max(dp)
0
0166621m2 months ago
C++ code using longest increasing approach
class box{
    public:
    int l,r,h;
    void setBox(int a,int b,int c)
    {
        l=a;
        r=b;
        h=c;
    }
    void print()
    {
        cout<<l<<" "<<r<<" "<<h<<endl;
    }
};
bool cmp(box a,box b)
{
    return (a.l * a.r) < (b.l * b.r);
}

class Solution{
    public:
    /*The function takes an array of heights, width and 
    length as its 3 arguments where each index i value 
    determines the height, width, length of the ith box. 
    Here n is the total no of boxes.*/
    int maxHeight(int h[],int w[],int l[],int n)
    {
        //Your code here
        box b[3*n];int j=0;
        for(int i=0;i<n;i++)
        {
            b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]);
            b[j++].setBox(min(w[i],l[i]),max(w[i],l[i]),h[i]);
            b[j++].setBox(min(l[i],h[i]),max(l[i],h[i]),w[i]);
        }
        n=n*3;
        sort(b,b+n,cmp);
        
        // for(int i=0;i<n;i++)
        // {
        //     b[i].print();
        // }
        
        int res[n];
        for(int i=0;i<n;i++)
        {
            res[i] = b[i].h;
        }
        
        int m =-1;
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<i;j++)
            {
                if(b[i].l > b[j].l && b[i].r > b[j].r && res[j] + b[i].h > res[i])
                res[i] = res[j] + b[i].h;
            }
            m = max(res[i],m);
        }
        
        return m;
    }
};
+1
bikrambiswas0436 months ago
 vector<array<int,3>>box(3*n);int k=0;for(int i=0;i<n;i++){ int arr[3]={length[i],width[i],height[i]}; sort(arr,arr+3); box[k++]={arr[0],arr[1],arr[2]}; box[k++]={arr[1],arr[2],arr[0]}; box[k++]={arr[0],arr[2],arr[1]};}sort(box.begin(),box.end(),[&](const array<int,3>&a,const array<int,3>&b){ return a[0]*a[1]<b[0]*b[1];}); vector<int>dp(3*n);int maxi=INT_MIN;for(int i=0;i<3*n;i++){ dp[i]=box[i][2]; for(int j=i-1;j>=0;j--){  if(box[j][0]<box[i][0]&&box[j][1]<box[i][1]){   dp[i]=max(dp[i],dp[j]+box[i][2]);  } } maxi=max(maxi,dp[i]);}return maxi;
+2
abhinavsingh26 months ago
23 24 56 9
for this input expected output is 15.
Can anyone tell me. how?
+3
rainx6 months ago
C++ CODE
 
 
//STRUCTURE FOR BOX, EMPTY CONSTRUCTOR USED FOR ARRAY                                                                FORMATION

struct Box{
    int l;
    int w;
    int h;
    Box(){}
    Box(int l, int w, int h){
        this->l=l;
        this->w=w;
        this->h=h;        
    }
};
//comparator function for sorting

bool cmp(Box &A, Box &B){
    return A.l*A.w > B.l*B.w;
}
int maxHeight(int height[],int width[],int length[],int n) {
        Box rot[3*n];
        int index=0;
        n=3*n;
//ALL ROTATIONS

for(int i=0;i<n;i++){
            rot[index++]=Box(max(length[i],width[i]),min(length[i],width[i]),height[i]);
            rot[index++]=Box(max(height[i],length[i]),min(height[i],length[i]),width[i]);
            rot[index++]=Box(max(height[i],width[i]),min(height[i],width[i]),length[i]);
}

sort(rot,rot+n,cmp);  //sorting using comparator function
int msh[n];
for (int i=0;i<n;i++){
    msh[i] = rot[i].h;  //filling the array with curr heights
}
for (int i=1;i<n;i++){
    for (int j=0;j<i;j++){
       if(rot[i].w < rot[j].w && rot[i].l < rot[j].l){
               msh[i]=max(msh[i], msh[j]+rot[i].h);
       }
    }
}


int mx = -1;
for (int i=0;i<n;i++){
     mx=max(mx,msh[i]);
}
   return mx;
}
HAPPY CODING :))
 
 
 
0
Bayabongo8 months ago
Bayabongo
[Python 3]  https://uploads.disquscdn.c...
0
delectable_boomer8 months ago
delectable_boomer
We can also sort based on width and length because at the end you want to place box i on box j if box[j].width > box[i].width and same for length. https://ideone.com/tkHhi2
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.