Equal Stacks


Problem Statement :


ou 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.

Input Format

The first line contains three space-separated integers,  n1 ,  n2 , and n3, 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 bottom:

The second line contains n1 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.
The third line contains n2 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.
The fourth line contains n3 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.

Note: An empty stack is still a stack.

Function Description

Complete the equalStacks function in the editor below.

equalStacks has the following parameters:

int h1[n1]: 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



Solution :



title-img


                            Solution in C :

In C++ :




#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(int i = (a); i >= (b); --i)
#define RI(i,n) FOR(i,1,(n))
#define REP(i,n) FOR(i,0,(n)-1)
#define mini(a,b) a=min(a,b)
#define maxi(a,b) a=max(a,b)
#define mp make_pair
#define pb push_back
#define st first
#define nd second
#define sz(w) (int) w.size()
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
const int inf = 1e9 + 5;
const int nax = 1e6 + 5;



int main() {
	int aa, bb, cc;
	scanf("%d%d%d", &aa, &bb, &cc);
	vi a, b, c;
	REP(_, aa) {
		int x;
		scanf("%d", &x);
		a.pb(x);
	}
	REP(_, bb) {
		int x;
		scanf("%d", &x);
		b.pb(x);
	}
	REP(_, cc) {
		int x;
		scanf("%d", &x);
		c.pb(x);
	}
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	reverse(c.begin(), c.end());
	ll A = 0, B = 0, C = 0;
	for(int x : a) A += x;
	for(int x : b) B += x;
	for(int x : c) C += x;
	while(A != B || A != C) {
		if(A == max(max(A, B), C)) {
			A -= a.back();
			a.pop_back();
		}
		else if(B == max(max(A, B), C)) {
			B -= b.back();
			b.pop_back();
		}
		else {
			C -= c.back();
			c.pop_back();
		}
	}
	printf("%lld\n", A);
	return 0;
}









In Java :




/* Andy Rock
 * June 25, 2016
 * 
 * World CodeSprint #4
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		StringTokenizer st = new StringTokenizer(in.readLine());
		int[] n =
		{
			Integer.parseInt(st.nextToken()),
			Integer.parseInt(st.nextToken()),
			Integer.parseInt(st.nextToken())
		};

		int[][] h = new int[3][];
		int[] sum = new int[3];
		for(int i=0;i<3;i++)
		{
			st = new StringTokenizer(in.readLine());
			h[i] = new int[n[i]];
			for(int j=0;j<n[i];j++)
			{
				h[i][j] = Integer.parseInt(st.nextToken());
				sum[i] += h[i][j];
			}
		}

		int[] pos = new int[3];
		while(true)
		{
			for(int i=0;i<3;i++)
				if(sum[i] > Math.min(sum[0], Math.min(sum[1], sum[2])))
				{
					sum[i] -= h[i][pos[i]];
					pos[i]++;
				}
			if(sum[0] == sum[1] && sum[1] == sum[2])
				break;
		}

		System.out.println(sum[0]);
	}
}








In C :




#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int n1,n2,n3,i,j=0,k=0,s1=0,s2=0,s3=0;
    scanf("%d %d %d",&n1,&n2,&n3);
    int arr1[n1];
    int arr2[n2];
    int arr3[n3];
    for(i=0;i<n1;i++){
        scanf("%d",&arr1[i]);
        s1+=arr1[i];
    }
    for(i=0;i<n2;i++){
        scanf("%d",&arr2[i]);
        s2+=arr2[i];
    }
    for(i=0;i<n3;i++){
        scanf("%d",&arr3[i]);
        s3+=arr3[i];
    }
    i=0;
    while(1){
        if((s1==s2 && s2==s3) || s1==0 || s2==0 || s3==0)
            break;
        if(s1>=s2 && s1>=s3)
            s1-=arr1[i++];
        else if(s2>=s1 && s2>=s3)
            s2-=arr2[j++];
        else
            s3-=arr3[k++];
    }
    if(s1==0 || s2==0 || s3==0)
        printf("0");
    else
        printf("%d",s1);
    return 0;
}









In Python3 :





def read_stack():
    stack = [int(x) for x in input().split(' ')]
    stack = list(reversed(stack))
    sum_stack = set()
    psum = 0
    for i in range(len(stack)):
        psum += stack[i]
        sum_stack.add(psum)
    return sum_stack

input()

ans = read_stack()
ans &= read_stack()
ans &= read_stack()
if len(ans) > 0:
    print(max(ans))
else:
    print(0)
                        








View More Similar Problems

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →