소프트웨어에 대한 모든 것

LeetCode 풀기 - 1913. Maximum Product Difference Between Two Pairs 본문

알고리즘/LeetCode

LeetCode 풀기 - 1913. Maximum Product Difference Between Two Pairs

앤테바 2021. 11. 5. 19:59
반응형

1913. Maximum Product Difference Between Two Pairs

https://leetcode.com/problems/maximum-product-difference-between-two-pairs/

 

Maximum Product Difference Between Two Pairs - 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)
  • 공간 복잡도 : O(1)
class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()
        return nums[-1] * nums[-2] - nums[0] * nums[1]

솔루션2)

  • 시간 복잡도 : O(n)
  • 공간 복잡도 : O(1)
class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        min1, min2 = 10000, 10000
        max1, max2 = 1, 1
        
        for n in nums:
            if n < min1:
                min1, min2 = n, min1
            elif n < min2:
                min2 = n
                
            if n > max2:
                max1, max2 = max2, n
            elif n > max1:
                max1 = n
        return max1 * max2 - min1 * min2

 

반응형
Comments