Suppose we have some rocks, each rock has a positive integer weight. In each turn, we will take two heaviest rocks and smash them together. consider the stones have weights x and y and x <= y. The result of this smash is can be of two types.
Finally, there is at most 1 stone left. We have to find the weight of this stone (0 when there are no stones left.)
So if the stone weights are [2,7,4,1,8,1], then the result will be 1. At first select 7 and 8, then get 1, so array will be [2,4,1,1,1], secondly take 2 and 4. The array will be [2,1,1,1], after that select 2 and 1, array will be [1,1,1], then select two stones with weight 1, then both will be destroyed, so array will be [1]. This is the answer
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def lastStoneWeight(self, stones): """ :type stones: List[int] :rtype: int """ if len(stones) ==0: return 0 if len(stones) == 1: return 1 while len(stones)>1: stones.sort() s1,s2=stones[-1],stones[-2] if s1==s2: stones.pop(-1) stones.pop(-1) else: s1 = abs(s1-s2) stones.pop(-1) stones[-1] = s1 if len(stones): return stones[-1] return 0 ob1 = Solution() print(ob1.lastStoneWeight([2,7,4,1,6,1]))
[2,7,4,1,6,1]
1