Equal Stacks in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank, Algorithm Solutions of Problem Solving Section in Java. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Equal Stacks in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Introduction To Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results. 

Advantages of Algorithms:

  • It is easy to understand.
  • Algorithm is a step-wise representation of a solution to a given problem.
  • In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Link for the ProblemEqual Stacks – Hacker Rank Solution

Equal Stacks– Hacker Rank Solution

Problem:

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

There are  and  cylinders in the three stacks, with their heights in the three arrays. Remove the top 2 cylinders from  (heights = [1, 2]) and from  (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, , , and , the numbers of cylinders in stacks , , and . The subsequent lines describe the respective heights of each cylinder in a stack from top to bottom:

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

Constraints

image 105

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  and , and then remove the top two cylinders from stack  (shown below).

modified stacks

The stack heights are reduced as follows:

image 104
Equal Stacks – Hacker Rank Solution
import java.util.Scanner;
import java.util.Stack;

/**
 * @author Techno-RJ
 *
 */
public class EqualStacks {
	static int equalStacks(int[] h1, int[] h2, int[] h3) {

		Stack<Integer> st1 = new Stack<Integer>();
		Stack<Integer> st2 = new Stack<Integer>();
		Stack<Integer> st3 = new Stack<Integer>();

		int st1TotalHeight = 0, st2TotalHeight = 0, st3TotalHeight = 0;

		// pushing consolidated height into the stack instead of individual cylinder
		// height
		for (int i = h1.length - 1; i >= 0; i--) {
			st1TotalHeight += h1[i];
			st1.push(st1TotalHeight);
		}
		for (int i = h2.length - 1; i >= 0; i--) {
			st2TotalHeight += h2[i];
			st2.push(st2TotalHeight);
		}
		for (int i = h3.length - 1; i >= 0; i--) {
			st3TotalHeight += h3[i];
			st3.push(st3TotalHeight);
		}

		while (true) {

			// If any stack is empty
			if (st1.isEmpty() || st2.isEmpty() || st3.isEmpty())
				return 0;

			st1TotalHeight = st1.peek();
			st2TotalHeight = st2.peek();
			st3TotalHeight = st3.peek();

			// If sum of all three stack are equal.
			if (st1TotalHeight == st2TotalHeight && st2TotalHeight == st3TotalHeight)
				return st1TotalHeight;

			// Finding the stack with maximum sum and
			// removing its top element.
			if (st1TotalHeight >= st2TotalHeight && st1TotalHeight >= st3TotalHeight)
				st1.pop();
			else if (st2TotalHeight >= st1TotalHeight && st2TotalHeight >= st3TotalHeight)
				st2.pop();
			else if (st3TotalHeight >= st2TotalHeight && st3TotalHeight >= st1TotalHeight)
				st3.pop();
		}

	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n1 = in.nextInt();
		int n2 = in.nextInt();
		int n3 = in.nextInt();
		int h1[] = new int[n1];
		for (int h1_i = 0; h1_i < n1; h1_i++) {
			h1[h1_i] = in.nextInt();
		}
		int h2[] = new int[n2];
		for (int h2_i = 0; h2_i < n2; h2_i++) {
			h2[h2_i] = in.nextInt();
		}
		int h3[] = new int[n3];
		for (int h3_i = 0; h3_i < n3; h3_i++) {
			h3[h3_i] = in.nextInt();
		}
		System.out.println(equalStacks(h1, h2, h3));
		in.close();
	}
}

48 thoughts on “Equal Stacks in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]”

  1. Tһis is very interesting, You’re a very skilled bloɡger.
    I hɑve joined your feеd and lоoҝ f᧐rward to
    seeқing more of your magnificent post. Also, I’ve shared үour website in my sociaⅼ networks!

    Reply
  2. Hi, i think that i saw you visited my web site thus i got
    here to go back the choose?.I am attempting to in finding issues to improve my web site!I assume its adequate to use a few of your ideas!!

    Reply
  3. I know this if off topic but I’m looking into starting my own blog and
    was wondering what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very web smart so I’m not 100% certain. Any recommendations or
    advice would be greatly appreciated. Thanks

    Reply
  4. obviously like your web site however you need to take a look at the spelling on several of your posts.
    Several of them are rife with spelling issues
    and I in finding it very troublesome to inform the reality nevertheless I’ll definitely come back again.

    Reply
  5. An impressive share! I’ve just forwarded this onto a coworker who was doing a little research on this.

    And he in fact ordered me lunch due to the fact that I discovered it for him…
    lol. So allow me to reword this…. Thanks for
    the meal!! But yeah, thanx for spending the time to discuss this subject here on your web site.

    Reply
  6. With havin so much content and articles do you ever run into any
    issues of plagorism or copyright infringement?

    My blog has a lot of exclusive content I’ve either written myself or
    outsourced but it seems a lot of it is popping it up all over the web without my agreement.
    Do you know any techniques to help stop content from being ripped off?
    I’d really appreciate it.

    Reply
  7. I enjoy what you guys tend to be up too. This type of clever work and exposure!
    Keep up the superb works guys I’ve included you guys
    to my personal blogroll.

    Reply
  8. This is very interesting, You are a very skilled blogger.

    I have joined your feed and look forward to seeking more of
    your wonderful post. Also, I have shared your web site
    in my social networks!

    Reply
  9. Do you have a spam issue on this blog; I also am a
    blogger, and I was wondering your situation; we have created some
    nice methods and we are looking to swap techniques with others,
    please shoot me an email if interested.

    Reply
  10. Oh my goodness! Amazing article dude! Thank you, However I
    am encountering issues with your RSS. I don’t know the reason why I
    can’t subscribe to it. Is there anybody getting the same RSS problems?

    Anyone who knows the answer can you kindly respond?
    Thanx!!

    Reply
  11. Hello there, just became aware of your blog through Google, and found that it’s
    truly informative. I’m going to watch out for brussels.

    I’ll be grateful if you continue this in future. Numerous people will be benefited from your
    writing. Cheers!

    Reply
  12. Can I simply just say what a comfort to find someone who genuinely understands what they’re talking about online. You certainly know how to bring a problem to light and make it important. More people must read this and understand this side of the story. I can’t believe you aren’t more popular because you most certainly possess the gift.

    Reply
  13. Hello there! Do you know if they make any plugins to help with SEO?

    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Appreciate it!

    Reply
  14. Hi my loved one! I wish to say that this post is amazing, great written and come with approximately all vital
    infos. I would like to peer extra posts like this .

    Reply
  15. Howdy! I simply would like to offer you a big thumbs up for the great information you have got right here
    on this post. I’ll be returning to your web site for more soon.

    Reply
  16. We’re a bunch of volunteers and starting a new scheme in our community.

    Your site offered us with helpful information to work on. You
    have done a formidable job and our whole community shall be grateful to you.

    Reply
  17. Hi there! I just wanted to ask if you ever have any problems
    with hackers? My last blog (wordpress) was hacked and I
    ended up losing a few months of hard work due to
    no backup. Do you have any solutions to stop hackers?

    Reply
  18. I was wondering if you ever considered changing the page
    layout of your website? Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content
    so people could connect with it better. Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

    Reply
  19. It is in point of fact a great and helpful piece of information. I am satisfied that you shared
    this useful information with us. Please keep us informed like this.
    Thanks for sharing.

    Reply
  20. Абузоустойчивый VPS
    Виртуальные серверы VPS/VDS: Путь к Успешному Бизнесу

    В мире современных технологий и онлайн-бизнеса важно иметь надежную инфраструктуру для развития проектов и обеспечения безопасности данных. В этой статье мы рассмотрим, почему виртуальные серверы VPS/VDS, предлагаемые по стартовой цене всего 13 рублей, являются ключом к успеху в современном бизнесе

    Reply
  21. https://medium.com/@Guillermin89329/бесплатный-vps-с-выделенным-сервером-на-ubuntu-linux-c4509878b2fa
    VPS SERVER
    Высокоскоростной доступ в Интернет: до 1000 Мбит/с
    Скорость подключения к Интернету — еще один важный фактор для успеха вашего проекта. Наши VPS/VDS-серверы, адаптированные как под Windows, так и под Linux, обеспечивают доступ в Интернет со скоростью до 1000 Мбит/с, что гарантирует быструю загрузку веб-страниц и высокую производительность онлайн-приложений на обеих операционных системах.

    Reply
  22. https://medium.com/@vivienne2274/ультра-быстрый-выделенный-сервер-с-ssd-накопителями-3fb2ebe42fb4
    VPS SERVER
    Высокоскоростной доступ в Интернет: до 1000 Мбит/с
    Скорость подключения к Интернету — еще один важный фактор для успеха вашего проекта. Наши VPS/VDS-серверы, адаптированные как под Windows, так и под Linux, обеспечивают доступ в Интернет со скоростью до 1000 Мбит/с, что гарантирует быструю загрузку веб-страниц и высокую производительность онлайн-приложений на обеих операционных системах.

    Reply
  23. Tiêu đề: “B52 Club – Trải nghiệm Game Đánh Bài Trực Tuyến Tuyệt Vời”

    B52 Club là một cổng game phổ biến trong cộng đồng trực tuyến, đưa người chơi vào thế giới hấp dẫn với nhiều yếu tố quan trọng đã giúp trò chơi trở nên nổi tiếng và thu hút đông đảo người tham gia.

    1. Bảo mật và An toàn
    B52 Club đặt sự bảo mật và an toàn lên hàng đầu. Trang web đảm bảo bảo vệ thông tin người dùng, tiền tệ và dữ liệu cá nhân bằng cách sử dụng biện pháp bảo mật mạnh mẽ. Chứng chỉ SSL đảm bảo việc mã hóa thông tin, cùng với việc được cấp phép bởi các tổ chức uy tín, tạo nên một môi trường chơi game đáng tin cậy.

    2. Đa dạng về Trò chơi
    B52 Play nổi tiếng với sự đa dạng trong danh mục trò chơi. Người chơi có thể thưởng thức nhiều trò chơi đánh bài phổ biến như baccarat, blackjack, poker, và nhiều trò chơi đánh bài cá nhân khác. Điều này tạo ra sự đa dạng và hứng thú cho mọi người chơi.

    3. Hỗ trợ Khách hàng Chuyên Nghiệp
    B52 Club tự hào với đội ngũ hỗ trợ khách hàng chuyên nghiệp, tận tâm và hiệu quả. Người chơi có thể liên hệ thông qua các kênh như chat trực tuyến, email, điện thoại, hoặc mạng xã hội. Vấn đề kỹ thuật, tài khoản hay bất kỳ thắc mắc nào đều được giải quyết nhanh chóng.

    4. Phương Thức Thanh Toán An Toàn
    B52 Club cung cấp nhiều phương thức thanh toán để đảm bảo người chơi có thể dễ dàng nạp và rút tiền một cách an toàn và thuận tiện. Quy trình thanh toán được thiết kế để mang lại trải nghiệm đơn giản và hiệu quả cho người chơi.

    5. Chính Sách Thưởng và Ưu Đãi Hấp Dẫn
    Khi đánh giá một cổng game B52, chính sách thưởng và ưu đãi luôn được chú ý. B52 Club không chỉ mang đến những chính sách thưởng hấp dẫn mà còn cam kết đối xử công bằng và minh bạch đối với người chơi. Điều này giúp thu hút và giữ chân người chơi trên thương trường game đánh bài trực tuyến.

    Hướng Dẫn Tải và Cài Đặt
    Để tham gia vào B52 Club, người chơi có thể tải file APK cho hệ điều hành Android hoặc iOS theo hướng dẫn chi tiết trên trang web. Quy trình đơn giản và thuận tiện giúp người chơi nhanh chóng trải nghiệm trò chơi.

    Với những ưu điểm vượt trội như vậy, B52 Club không chỉ là nơi giải trí tuyệt vời mà còn là điểm đến lý tưởng cho những người yêu thích thách thức và may mắn.

    Reply
  24. VPS SERVER
    Высокоскоростной доступ в Интернет: до 1000 Мбит/с
    Скорость подключения к Интернету — еще один важный фактор для успеха вашего проекта. Наши VPS/VDS-серверы, адаптированные как под Windows, так и под Linux, обеспечивают доступ в Интернет со скоростью до 1000 Мбит/с, что гарантирует быструю загрузку веб-страниц и высокую производительность онлайн-приложений на обеих операционных системах.

    Reply

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock