m1ndy5's coding blog

LeetCode 1464. Maximum Product of Two Elements in an Array with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 1464. Maximum Product of Two Elements in an Array with Python

정민됴 2024. 1. 5. 10:40

https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/

python heapq는 기본적으로 minheap구조로 되어있다.
따라서 max값을 구하고 싶을 때는 -1을 곱해서 힙에 넣고 최솟값을 뺀 뒤 다시 -1을 곱해주면 된다.

import heapq

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        nums = [-1 * num for num in nums]
        heapq.heapify(nums)
        # -1를 곱했기 때문에 1을 빼려면 1을 더해주면 된다 혹은 리턴할 때 1을 빼고 곱해주거나!
        a = heapq.heappop(nums)+1
        b = heapq.heappop(nums)+1

        return a*b

sort로 풀었어도 크게 문제 없는 문제였다.