파이썬 코딩테스트/해커랭크
HackerRank / Beautiful Pairs / Python
S.T.Lee
2021. 12. 11. 22:31
https://www.hackerrank.com/challenges/beautiful-pairs/problem
두개의 리스트가 주어졌을 때, 두 리스트에 겹치는 값을 Beautiful Pairs라하며 index의 묶음으로 표현한다.
예를 들어, A = [10, 11, 12, 5, 14] B = [8, 9, 11, 11, 5]라고 했을 때 Beautiful Pairs는 [(1,2), (1,3), (3,4)]이다.
무조건 딱 하나의 값을 바꿔서 Beautiful Pairs의 개수를 변화 시킬 것이다.
( Your task is to change exactly 1 element in so that the size of the pairwise disjoint beautiful set is meximum.)
이 경우 B의 0번째 인덱스를 10으로 바꾸면 된다.
그러면 4개의 Beautiful Pairs를 얻을 수 있다.
2번째 예시를 통해 같은 갑은 겹쳐도 됨을 확인할 수 있다.
A = [3, 5, 7, 11, 5, 8] B=[5, 7, 11, 10, 5, 8]을 주는데 아웃풋이 6이다.
즉, 5의 인덱스에 해당하는 (1,0),(4,4)를 따로 쳐주고 3,10을 바꾼 것이다.
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'beautifulPairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY B
#
def beautifulPairs(A, B):
# Write your code here
n = 0
for i in A:
if i in B:
B.remove(i) #B와 A에 중복되는 숫자 제거
n += 1
if n < len(A):
return n+1 # 무조건 하나를 바꿔 쌍을 맞출 수 있음으로 1 증가
else:
return n-1 # 전부 다 같아도 무조건 하나를 바꿔야하므로 1 감소
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
A = list(map(int, input().rstrip().split()))
B = list(map(int, input().rstrip().split()))
result = beautifulPairs(A, B)
fptr.write(str(result) + '\n')
fptr.close()