Maximum Product of Two Elements in an Array - LeetCode
Can you solve this real interview question? Maximum Product of Two Elements in an Array - Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: Inpu
leetcode.com
문제
정수 배열이 주어지면 해당 배열의 두 가지 다른 인덱스를 선택후 그 곱의 최대값을 반환합니다.
과정
- 가장 큰값과 두 번째로 큰값을 찾아 각 값에서 -1을 해준 후 곱한 결과를 리턴한다.
- sorted를 이용하는 방법과 heapq를 이용하는 방법이 있다.
입력
[3,4,5,2]
출력
12
풀이
class Solution:
def maxProduct(self, nums: List[int]) -> int:
n = sorted(nums, reverse=True)
return (n[0]-1)*(n[1]-1)
한 줄씩 코드 해석해보기
n = sorted(nums, reverse=True)
- 입력받은 배열을 큰 수부터 정렬한다.
return (n[0]-1)*(n[1]-1)
- 정렬된 배열에서 첫번째 값과 두번째 값에서 -1을 뺀 값을 곱한 후 리턴 해준다.
힙을 이용한 풀이
class Solution:
def maxProduct(self, nums: List[int]) -> int:
h = heapq.nlargest(2, nums)
return (h[0] - 1) * (h[1] - 1)
- nlargest() : 가장 큰 값부터 순서대로 리스트에 넣어준다
sorted를 이용하는 방법은 시간 복잡도가 O(NlogN)이고, heapq는 O(logN)이기 때문에 힙이 더 빠르다.
'코딩 테스트 (Python) > 리트코드' 카테고리의 다른 글
[리트코드] 234. 펠린드롬 연결 리스트 (Python) (1) | 2024.01.08 |
---|---|
[리트코드] 1337. 행렬의 K개 가장 약한 행 (Python) (0) | 2024.01.06 |
[리트코드] 215. 배열의 K번째 큰 요소 (Python) (1) | 2024.01.06 |
[리트코드] 347. 상위 K 빈도 요소 (Python) (1) | 2024.01.05 |
[리트코드] 3. 중복 문자가 없는 가장 긴 부분 문자열 (Python) (0) | 2024.01.05 |