Equal Stacks| Stack
TASK
You 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. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they are all the same height, then return the height.
Example
h1- [1,2,1,1]
h2- [1,1,2]
h3= [1,1]
There are 4, 3 and 2 cylinders in the three stacks, with their heights in the three arrays. Remove the top 2 cylinders from h1 (heights = [1, 2]) and from h2 (heights = [1, 1]) so that the three stacks all are 2 units tall. Return 2 as the answer.
Note: An empty stack is still a stack.
Function Description
Complete the equalStacks function in the editor below.
equalStack has the following parameters:
int hl[nl]: the first array of heights
int h2[n2]: the second array of heights
int h3[n3]: the third array of heights
Returns
int: the height of the stacks when they are equalized
Input Format
The first line contains three space-separated integers, n1, n2, and 13. the numbers of cylinders in stackS 1, 2, and 3. The subsequent lines describe the respective heights of each cylinder in a stack from top to bottorre
The second line contains n1 space-separated integers, the cylinder heights in stack 1. The first element is the top cylinder of the stack
The third line contains n2 space-separated integers, the cylinder heights in stack 2. The first element is the top cylinder of the stack.
The fourth line contains n3 space-separated integers, the cylinder heights in stack 3. The first element is the top cylinder of the stack.
Constraints
1. 0<n1, n2, n≤ 105
2. 0<height of any cylinder ≤ 100
Sample Input
STDIN Function
534 h1[] size n 5, h2[] size n2 = 3, h3[] size n3 = 4
32111 hl [3, 2, 1, 1, 1]
432 h2 [4, 3, 2]
1141 h3= [1, 1, 4, 1]
Sample Output
5
Solution 1
def sumHeight(h):
if h is None: return 0
else: return sum(h)
def equalStacks(h1, h2, h3):
height1 = sumHeight(h1)
height2 = sumHeight(h2)
height3 = sumHeight(h3)
while(1):
if height1 == height2 and height2 == height3: return height1
highestHeight = max(max(height1, height2), height3)
if highestHeight == height1: height1 -= h1.pop(0)
elif highestHeight == height2: height2 -= h2.pop(0)
elif highestHeight == height3: height3 -= h3.pop(0)
return -1