Last Stone Weight Problem Explanation

Given a collection of stones, each having a positive integer weight, perform the following operation: On each turn, select the two heaviest stones and smash them together. Assume the stones have weights 'x' and 'y' where 'x' <= 'y'. The outcomes of smashes are:

  1. If 'x' == 'y', both stones are destroyed.
  2. If 'x' != 'y', the stone with weight 'x' is destroyed, and the stone with weight 'y' is updated to 'y - x'.

Continue this process until at most one stone remains. Return the weight of the last stone, or 0 if no stones are left.

Input:

First line: Integer 'N', the number of stones.
Second line: 'N' space-separated integers representing the weights of the stones.

Output:

Print the weight of the final stone, or 0 if no stones remain.

Example:

Input: 
N = 6
Weights = [2, 7, 4, 1, 8, 1]

Output:
1

Constraints:

  • 1 <= N <= 10^5
  • 1 <= W[i] <= 10^6
  • Time Limit: 1 sec

Note:

Implement the function to solve the problem. No need for explicit printing or input reading as it's handled internally.

AnswerBot
10d

Implement a function to find the weight of the last stone remaining after smashing the heaviest stones together.

  • Create a max heap to store the weights of stones.

  • Repeatedly pop the two heaviest stones,...read more

Help your peers!
Add answer anonymously...
Encore Capital Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter