1 minute read

1046. Last Stone Weight (easy)

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        heap = []
        for stone in stones:
            heappush(heap, -stone)

        while len(heap) >= 2:
            # print(heap)
            a, b = -heappop(heap), -heappop(heap)
            if a > b:
                heappush(heap, b - a)
        
        # print(heap)
        return -heap[0] if heap else 0

2149. Rearrange Array Elements by Sign (medium)

class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        pos, neg = [], []
        for num in nums:
            if num > 0: pos.append(num)
            if num < 0: neg.append(num)
        
        res = []
        n = len(pos)
        for i in range(n):
            res.append(pos[i])
            res.append(neg[i])
        
        return res

376. Wiggle Subsequence (medium)

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 2:
            return n
        
        # Initialize variables to keep track of the length of the longest 
        # wiggle subsequence and the last wiggle direction
        max_len = 1
        last_wiggle = None
        
        for i in range(1, n):
            # Calculate the difference between the current and previous element
            diff = nums[i] - nums[i-1]
            # If the difference is positive and the last wiggle direction was negative
            # or the difference is negative and the last wiggle direction was positive,
            # then we've found a new wiggle direction and can update the length of the 
            # longest wiggle subsequence
            if (diff > 0 and last_wiggle != 1) or (diff < 0 and last_wiggle != -1):
                max_len += 1
                # Update the last wiggle direction
                last_wiggle = 1 if diff > 0 else -1
                
        return max_len