미소를뿌리는감자의 코딩
[leetcode 2024/02/08] 1464. Maximum Product of Two Elements in an Array 본문
코딩 테스트/leetcode
[leetcode 2024/02/08] 1464. Maximum Product of Two Elements in an Array
미뿌감 2024. 2. 8. 11:50728x90
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1. 접근 방법
이번 문제는 list에서 가장 큰 값 2개 (x, y 라고 하자) 를 구한 후 (x-1)*(y-1)을 return 하는 것이다.
문제 접근 방법은 여러가지가 있다.
1. heap에서 꺼내는 방법
2. 정렬 후 꺼내는 방법
3. max 값을 구하고 remove 하는 방법
속도적인 측면에서는 3 -> 2 -> 1 로 좋다. 메모리 측면에서는 비슷비슷 했다.
heap이 빠를 줄 알았지만, python에서는 heap이 더 느릴수도 있구나.. 라고 생각이 든다. 언어마다 optimal 한 것이 다른 것 같다.
바로 코드로 넘어가도록 하겠다.
2. 코드
예제1: heap에서 꺼내는 방법
class Solution:
def maxProduct(self, nums: List[int]) -> int:
largest_k = heapq.nlargest(2, nums)
return (largest_k[0]-1)*(largest_k[1]-1)
예제2: 정렬 후 꺼내는 방법
class Solution:
def maxProduct(self, nums: List[int]) -> int:
nums.sort(reverse = True)
return (nums[0]-1)*(nums[1]-1)
예제3: max 값을 구하고 remove 하는 방법
class Solution:
def maxProduct(self, nums: List[int]) -> int:
max1 = max(nums)
nums.remove(max1)
max2 = max(nums)
return (max1-1)*(max2-1)
728x90
'코딩 테스트 > leetcode' 카테고리의 다른 글
[leetcode 2024/02/08] 215. Kth Largest Element in an Array (0) | 2024.02.08 |
---|---|
[leetcode 2024/02/08] 1337. The K Weakest Rows in a Matrix (0) | 2024.02.08 |
[leetcode 2024/02/07] 347. Top K Frequent Elements - heapq.nlargest (1) | 2024.02.07 |
[leetcode 2024/02/07] 3.Longest Substring Without Repeating Characters (0) | 2024.02.07 |
[leetcode 2024/02/07] 771. Jewels and Stones (0) | 2024.02.07 |