Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones.

You are given an array of integers stones where stones[i] is the weight of the ith stone.

We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

If x == y, both stones are destroyed, and

If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.

At the end of the game, there is at most one stone left.

Return the weight of the last remaining stone. If there are no stones left, return 0. Hint: May be Max Heap will help you to solve this problem. Use maxheap.

public class MaxHeapDemo {

public static void main(String[] args) {

MaxHeap maxHeap = new MaxHeap();

int[] numbers = { 10, 2, 5, 18, 22 };

// Add all numbers to the heap

for (int number : numbers) {

maxHeap.insert(number);

System.out.printf(" --> array: %s ", maxHeap.getHeapArrayString());

}

while (maxHeap.getHeapSize() > 0) {

int removedValue = maxHeap.remove();

System.out.printf(" --> removed %d, array: %s ", removedValue,

maxHeap.getHeapArrayString());

}

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Jeff Hoffer, Ramesh Venkataraman, Heikki Topi

12th edition

133544613, 978-0133544619

More Books

Students also viewed these Databases questions

Question

5. Benchmark current training practices.

Answered: 1 week ago