[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits (Python)

2025. 2. 12. 15:02·코딩 테스트
728x90

Problem

 

Solution

Hash

 

보통 배열의 길이가 10^5 이하이면 2중 for문은 안쓰는게 상책. time out이 발생할 확률이 99%이기 때문

어떤 index인지는 i != j 조건만 만족하면 되므로 nums를 먼저 오름차순으로 정렬 후 시작한다.

동일한 sumDigit 을 가지는 인덱스를 hashMap으로 저장한 다음에 가장 마지막과 마지막에서 2번째 인덱스의 nums[i] + nums[j] 를 구하여 max 값을 갱신한다.

가장 마지막과 2번째로 마지막 인덱스를 구하는 이유는 처음에 오름차순 정렬을 했으므로 가장 뒤쪽의 인덱스일수록 nums[i]가 큰 정수값이기 때문이다.

 

Code

class Solution:
    def maximumSum(self, nums: List[int]) -> int:
        answer = -1
        map = defaultdict(list) #key= sum of digits, value= indicies
   
        nums.sort()

        def getSumOfDigit(num: int):
            res = 0
            while(num > 0):
                res += num%10
                num = num//10
            return res
        
        for i in range(len(nums)):
            sumDigit = getSumOfDigit(nums[i])
            map[sumDigit].append(i)
        
        for k,v in map.items():
            if len(v) >= 2:
                idx1 = v[-1]
                idx2 = v[-2]
                answer = max(nums[idx1] + nums[idx2], answer)
        return answer

 

Complexity

Time Complexity

nums.sort() -> O(nlogn)

for문 -> O(N)

 

Space Complexity

map dictionary -> O(N)

728x90
저작자표시 비영리 변경금지 (새창열림)

'코딩 테스트' 카테고리의 다른 글

[LeetCode] CodeTestcaseTestcaseTest Result1352. Product of the Last K Numbers (Python)  (0) 2025.02.14
[LeetCode] 3066. Minimum Operations to Exceed Threshold Value II (Python)  (0) 2025.02.13
[LeetCode] 1910. Remove All Occurrences of a Substring (Python)  (0) 2025.02.11
[LeetCode] 3174. Clear Digits (Python)  (0) 2025.02.10
[LeetCode] 2364. Count Number of Bad Pairs (Python)  (0) 2025.02.09
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] CodeTestcaseTestcaseTest Result1352. Product of the Last K Numbers (Python)
  • [LeetCode] 3066. Minimum Operations to Exceed Threshold Value II (Python)
  • [LeetCode] 1910. Remove All Occurrences of a Substring (Python)
  • [LeetCode] 3174. Clear Digits (Python)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자료구조
    springboot
    스프링부트
    리트코드
    db
    Spring
    알고리즘
    Python
    코테
    자바
    java
    코딜리티
    카카오코테
    kafka
    pythoncodingtest
    프로그래머스
    금융용어
    쿠버네티스
    코테공부
    이분탐색
    LeetCode
    codility
    네트워크
    코딩테스트
    CodingTest
    코딩
    Kotlin
    스프링
    C++
    MySQL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits (Python)
상단으로

티스토리툴바