Last Stone Weight in Python

PythonServer Side ProgrammingProgramming

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.

  • If x = y, then both stones are totally destroyed;
  • Otherwise when x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

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 −

  • If stone weight array W has no element, then return 0
  • If W has only one element then return the W[0]
  • while W has more than one elements −
    • sort W
    • s1 := last element of W, s2 := second last element of W
    • if s1 = s2, then remove s1 and s2 from W
    • otherwise s1 := |s1 – s2|, remove last element from W, then set s1 as last element of W
  • if W has one element, then return that element, otherwise return 0


Let us see the following implementation to get better understanding −

 Live Demo

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:
         if s1==s2:
            s1 = abs(s1-s2)
            stones[-1] = s1
      if len(stones):
         return stones[-1]
      return 0
ob1 = Solution()




Updated on 28-Apr-2020 17:36:07