HackerRank Sherlock and MiniMax
https://www.hackerrank.com/challenges/sherlock-and-minimax/problem
提出
Terminated due to timeout :(
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'sherlockAndMinimax' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY arr
# 2. INTEGER p
# 3. INTEGER q
#
def sherlockAndMinimax(arr, p, q):
# Write your code here
res = []
for i in range(p, q+1):
i_ans = float('inf')
for j in arr:
if (abs(i - j) < i_ans):
i_ans = abs(i - j)
res.append(i_ans)
ans = max(res)
return res.index(ans) + p
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
first_multiple_input = input().rstrip().split()
p = int(first_multiple_input0)
q = int(first_multiple_input1)
result = sherlockAndMinimax(arr, p, q)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'sherlockAndMinimax' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY arr
# 2. INTEGER p
# 3. INTEGER q
#
def sherlockAndMinimax(arr, p, q):
# Write your code here
arr = sorted(arr)
new_arr = []
minx = -1
ans = -1
if p < arr0:
if (arr0 - p) > minx:
minx = arr0 - p
ans = p
if q > arr-1:
if q - arr0 > minx:
minx = q - arr-1
ans = q
for i in range(0, len(arr)-1):
mid = (arri + arri+1) // 2
if mid <= q and mid >= p and (mid-arri) > minx:
minx = (mid - arri)
ans = mid
elif mid > q:
if (q - arri) > minx:
minx = (q - arri)
ans = q
elif mid < p:
if (arri+1 - p) > minx:
minx = (arri+1 - p)
ans = p
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
first_multiple_input = input().rstrip().split()
p = int(first_multiple_input0)
q = int(first_multiple_input1)
result = sherlockAndMinimax(arr, p, q)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=UOcfNW0sWkU
https://scrapbox.io/files/61d16da19363d3001debc648.png