소프트웨어에 대한 모든 것

LeetCode 풀기 - 1464. Maximum Product of Two Elements in an Array 본문

알고리즘/LeetCode

LeetCode 풀기 - 1464. Maximum Product of Two Elements in an Array

앤테바 2021. 11. 6. 10:10
반응형

1464. Maximum Product of Two Elements in an Array

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

 

Maximum Product of Two Elements in an Array - LeetCode

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)

  • O(nlogn)
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        nums.sort()
        return (nums[-1] - 1) * (nums[-2] - 1)

솔루션2)

  • O(n)
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        a, b = 0, 0
        
        for n in nums:
            if b < n:
                a, b = b, n
            elif a < n:
                a = n
        return (a-1) * (b-1)

 

반응형
Comments