For details about the problem, check this out - https://www.hackerrank.com/challenges/equal-stacks/problem
We have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times.
We need to find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means we must remove zero or more cylinders from the top of zero or more of the three stacks until they're all the same height, then print the height. The removals must be performed in such a way as to maximize the height.
I implemented the stacks using three vectors, and found out the sum of heights of cylinders in each of the three stacks. Now, I implemented the pop() function on each stack repeatedly until either one of the stack becomes empty or the sum of heights of cylinders in each stack becomes equal.
//My function that returns the maximum height:
int equalStacks(vector<int> h1, vector<int> h2, vector<int> h3)
{
int s1 = h1.size(), s2 = h2.size(), s3 = h3.size(), sum1 = 0,
sum2 = 0, sum3 = 0;
int i, j;
for(i = 0; i < s1; i++)
sum1 += h1[i];
for(i = 0; i < s2; i++)
sum2 += h2[i];
for(i = 0; i < s3; i++)
sum3 += h3[i];
int height = 0;
while(!h1.empty() && !h2.empty() && !h3.empty())
{
if(sum1 == sum2 && sum2 == sum3)
{
height = sum1;
return height;
}
sum1 -= h1.back();
sum2 -= h2.back();
sum3 -= h2.back();
h1.pop_back();
h2.pop_back();
h3.pop_back();
}
return height;
}
Sample input:
5 3 4
3 2 1 1 1
4 3 2
1 1 4 1
Expected output:
5
My program's output:
0
Aucun commentaire:
Enregistrer un commentaire