Tech for good

[Leetcode/Heap] 1464. Maximum Product of Two Elements in an Array 본문

IT/Computer Science

[Leetcode/Heap] 1464. Maximum Product of Two Elements in an Array

Diana Kang 2025. 3. 31. 23:05

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        # Convert to max-heap by pushing negative values
        max_heap = [-num for num in nums]
        heapq.heapify(max_heap)

        # Pop the two largest values
        first_max = -heapq.heappop(max_heap)
        second_max = -heapq.heappop(max_heap)

        return (first_max - 1) * (second_max - 1)