Algorithm


Problem Name: Data Structures - Equal Stacks

Problem Link: https://www.hackerrank.com/challenges/equal-stacks/problem?isFullScreen=true

In this HackerRank in Data Structures - Equal Stacks solutions

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

as the answer.

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

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

  • 0 <= n1,n2,n3 <= 10**5
  • 0 <= height of any cylinder <= 100

Sample Input

STDIN       Function
-----       --------
5 3 4       h1[] size n1 = 5, h2[] size n2 = 3, h3[] size n3 = 4  
3 2 1 1 1   h1 = [3, 2, 1, 1, 1]
4 3 2       h2 = [4, 3, 2]
1 1 4 1     h3 = [1, 1, 4, 1]

Sample Output

5

Explanation

Initially, the stacks look like this:

 

initial stacks

To equalize thier heights, remove the first cylinder from stacks 1 and 2 then remove the top two cylinders from stack 3 (shown below).

modified stacks

The stack heights are reduced as follows:

  1. 8 - 3 = 5
  2. 9 - 4 = 5
  3. 7 -1 -1 = 5

All three stacks now have height = 5, the value to return.

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


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

int findmax(int h1, int h2, int h3){
        int max;
    if(h1 == h2 && h2 == h3)
        return h1;
    max = (h1 > h2) ? 1:2;
    if(max == 1)
        max =(h1 > h3) ? 1:3;
    else
    max = (h2 > h3) ? 2:3;
return max;
}
int balance(int *N1, int * N2, int *N3, int h1, int h2, int h3, int n1, int n2, int n3){
    int k1, k2, k3;
    k1 =k2=k3=0;
    int  max = findmax(h1,h2,  h3);
    while(!(h1 == h2 && h2 == h3)){
        max=findmax(h1, h2, h3);
        if(max == 1)
            h1 -= N1[k1++];
        else
          if(max == 2)
            h2 -= N2[k2++];
            else
                if(max == 3)
                   h3 -= N3[k3++];
             //   printf("1:%d, 2:%d, 3:%d\n",h1, h2, h3);
        if(h1 == 0 || h2 == 0 || h3 == 0)
            return 0;
    }
    return h2;
}
int main() {
    int n1,n2, n3, h1, h2, h3,i;
    h1 = h2 = h3 = 0;
    scanf("%d %d %d",&n1, &n2, &n3);
    int *N1 = malloc(sizeof(int *)*n1);
    int *N2 = malloc(sizeof(int *)*n2);
    int *N3 = malloc(sizeof(int *)*n3);

    for(i = 0; i < n1; i++){
       scanf("%d", &N1[i]);
       h1 += N1[i];
    }
    for(i = 0; i  <  n2; i++){
       scanf("%d", &N2[i]);
       h2 += N2[i];
    }
    for(i = 0; i  <  n3; i++){
       scanf("%d", &N3[i]);
       h3 += N3[i];
    }
    printf("%d\n", balance(N1, N2, N3, h1, h2, h3, n1, n2,n3)>;
    
    return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include "bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int (i)=0;(i) < (int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i) < =(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i) < (int)(u);++(i))
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
typedef vector<int> vi; typedef pair < int, int> pii; typedef vector<pair<int, int> > vpii; typedef long long ll;
template < typename T, typename U> static void amin(T &x, U y) { if(y < x> x = y; }
template < typename T, typename U> static void amax(T &x, U y) { if(x < y) x = y; }

int main() {
    int n1; int n2; int n3;
    while(~scanf("%d%d%d", &n1, &n2, &n3)) {
        vector<int> a(n1);
        for(int i = 0; i  <  n1; ++ i)
            scanf("%d", &a[i]);
        vector<int> b(n2);
        for(int i = 0; i  <  n2; ++ i)
            scanf("%d", &b[i]);
        vector<int> c(n3);
        for(int i = 0; i  <  n3; ++ i)
            scanf("%d", &c[i]);
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        reverse(c.begin(), c.end()>;
        map < int, int> t;
        rep(k, 3) {
            const vi &v = k == 0 ? a : k == 1 ? b : c;
            int sum = 0;
            for(int x : v) {
                sum += x;
                ++ t[sum];
            }
        }
        int ans = 0;
        for(auto p : t) if(p.second == 3)
            amax(ans, p.first);
        printf("%d\n", ans);
    }
    return 0;
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


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

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        HashMap < Integer, ArrayList());
            for(int j=0 ; j  <  sn[i]; j++)
            {
                int k = in.nextInt();
                sum[i] += k;
                map.get(i).add(0,k);
            }
        }
        
        while (!((sum[0] == sum[1]) && (sum[1] == sum[2])))
        {
            int minSum = Math.max(Math.max(sum[0], sum[1]), sum[2]);
            int j = 0;
            if (minSum == sum[0])
                j =0;
            else if (minSum == sum[1])
                j = 1;
            else
                j = 2;
          
                sum[j] -=  map.get(j).get(map.get(j).size() - 1);
                map.get(j).remove(map.get(j).size() - 1);
            
        }
        
        System.out.println(sum[0]);
        
        
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var n1_temp = readLine().split(' ');
    var n1 = parseInt(n1_temp[0]);
    var n2 = parseInt(n1_temp[1]);
    var n3 = parseInt(n1_temp[2]);
    h1 = readLine().split(' ');
    h1 = h1.map(Number);
    h2 = readLine().split(' ');
    h2 = h2.map(Number);
    h3 = readLine().split(' ');
    h3 = h3.map(Number);
    
    ///////////
    
    var arrStack = [h1, h2, h3];
    var arrTopPointer = [0, 0, 0];
    var arrSum = [getHeight(h1), getHeight(h2), getHeight(h3)];

    var index = getMaxStackIndex(arrSum);
    while (index >= 0) {        
        arrSum[index] -= arrStack[index][arrTopPointer[index]];
        arrTopPointer[index]++;
        index = getMaxStackIndex(arrSum);
    }
    console.log(arrSum[0]);
}

function getMaxStackIndex(arrSum) {
    var hasMax = false;
    var maxVal = arrSum[0];
    var maxIndex = 0;
    for (var i = 1; i  <  arrSum.length; i++) {
        if (arrSum[i] > maxVal) {
            hasMax = true;
            maxVal = arrSum[i];
            maxIndex = i;
        } else if ((arrSum[i]  <  maxVal)) {
            hasMax = true;
        }
    }
    if (hasMax) {
        return maxIndex;
    } else {
        return -1;
    }
}

function getHeight(stack) {
    var sum = 0;
    for (var i = 0; i  <  stack.length; i++) {
        sum += stack[i];
    }
    return sum;
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


def check_equal_heights(heights):
    h_0 = heights[0]
    for h_i in heights[1:]:
        if h_i != h_0:
            return False
    return True


num_blocks = [int(num) for num in input().strip().split()]
num_stacks = len(num_blocks)
stacks = []
for __ in range(num_stacks):
    stack = [int(h) for h in input().strip().split()]
    stacks.append(stack[::-1])

goal = 1
best_height = 0
heights = [0] * num_stacks
positions = [0] * num_stacks
total_blocks = sum(num_blocks)
while sum(positions) < total_blocks:
    for i, stack in enumerate(stacks):
        if positions[i] == num_blocks[i]:
            continue
            
        if heights[i] == goal:
            heights[i] += stack[positions[i]]
            positions[i] += 1
        
        at_end = False
        while heights[i] < goal:
            if positions[i] == num_blocks[i]:
                at_end = True
                break
            heights[i] += stack[positions[i]]
            positions[i] += 1
            
        goal = heights[i]
            
        if at_end:
            continue
            
        if check_equal_heights(heights):
            best_height = heights[i]
            
print(best_height)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Jesse and Cookies solution in Hackerrank - Hacerrank solution C, C++, java,js, Python
Next
[Solved] Sparse Arrays solution in Hackerrank - Hacerrank solution C, C++, java,js, Python