Equal Stacks

  • + 0 comments

    Java O(n)

    public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
        int l1=0,l2=0,l3=0;
    
        Stack<Integer> h11= new Stack<Integer>();
        Stack<Integer> h12= new Stack<Integer>();
        Stack<Integer> h13= new Stack<Integer>();
    
        for(int i=h1.size()-1;i>=0;i--){
            l1+=h1.get(i);
            h11.push(h1.get(i));
        }
        for(int i=h2.size()-1;i>=0;i--){
            l2+=h2.get(i);
            h12.push(h2.get(i));
        }
        for(int i=h3.size()-1;i>=0;i--){
            l3+=h3.get(i);
            h13.push(h3.get(i));
        }
    
        while( l1!=l2 || l2!=l3){
    
            if(l1>l2 || l1>l3){
                l1-=h11.pop();
            }
            if(l2>l1 || l2>l3) {
                l2 -= h12.pop();
            }
            if(l3>l2 || l3>l1){
                l3-=h13.pop();
            }
        }
        return l1;
    }