본문 바로가기

Algorithm/Implementation

(Python3) - LeetCode (Easy) : 3536. Maximum Product of Two Digits

반응형

https://leetcode.com/problems/maximum-product-of-two-digits

 

Maximum Product of Two Digits - LeetCode

Can you solve this real interview question? Maximum Product of Two Digits - You are given a positive integer n. Return the maximum product of any two digits in n. Note: You may use the same digit twice if it appears more than once in n.   Example 1: Input

leetcode.com

구현 문제였습니다

📕 풀이방법

📔 입력 및 초기화

📑 입력받은 n을 한자리 별 원소로 저장할 배열 digits를 선언합니다

📔 풀이과정

📑 같은 자리가 아닌 두 정수의 최댓값은 가장 큰 두 원소의 곱입니다
따라서 n의 각 자릿수를 배열로 만든 뒤 내림차순으로 정렬했을 때 0,1 원소가 최댓값입니다.

📑 시간 복잡도

O(NlogN): 정렬을 내림차순으로 하기 때문

📑 공간 복잡도

O(N): n의 자릿수만큼의 배열을 선언하기 때문

📔 정답 출력 | 반환

첫 번째와 두 번째의 곱을 반환합니다


📕 Code

📔 Python3

class Solution:
    def maxProduct(self, n: int) -> int:
        digits = sorted(map(int, str(n)), reverse=True)
        return digits[0] * digits[1]

 


*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.