Posted on

Description

Submission

Submission

  • Following is not a simplified version
  • We don’t have to use real stacks, moving pointers(or indices) are enough
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

/*
 * Complete the equalStacks function below.
 */
int equalStacks(vector<int> h1, vector<int> h2, vector<int> h3) {
    /*
     * Write your code here.
     */
    int height1 = 0, height2 = 0, height3 = 0;
    stack<int> s1, s2, s3;
    for(int i = h1.size() - 1; i >= 0; --i) {
        height1 += h1[i];
        s1.push(h1[i]);
    }
    for(int i = h2.size() - 1; i >= 0; --i) {
        height2 += h2[i];
        s2.push(h2[i]);
    }
    for(int i = h3.size() - 1; i >= 0; --i) {
        height3 += h3[i];
        s3.push(h3[i]);
    }

    for(; height1 != height2 || height1 != height3 || height2 != height3; ) {
        if(height1 >= height2 && height1 >= height3) {
            height1 -= s1.top();
            s1.pop();
        } else if(height2 >= height1 && height2 >= height3) {
            height2 -= s2.top();
            s2.pop();
        } else if(height3 >= height1 && height3 >= height2) {
            height3 -= s3.top();
            s3.pop();
        }
    }
    return height1;
}

int main()
{
    int n1, n2, n3;
    cin >> n1 >> n2 >> n3;

    vector<int> h1(n1);

    for (int h1_itr = 0; h1_itr < n1; h1_itr++) {
        cin >> h1[h1_itr];
    }

    vector<int> h2(n2);

    for (int h2_itr = 0; h2_itr < n2; h2_itr++) {
        cin >> h2[h2_itr];
    }

    vector<int> h3(n3);

    for (int h3_itr = 0; h3_itr < n3; h3_itr++) {
        cin >> h3[h3_itr];
    }

    int result = equalStacks(h1, h2, h3);

    cout << result << "\n";

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *