본문 바로가기
CodeSignal/Arcade

CodeSignal [32/60] absoluteValuesSumMinimization

by 벤진[Benzene] 2020. 5. 22.

Problem: 

Given a sorted array of integers a, your task is to determine which element of a is closest to all other values of a. In other words, find the element x in a, which minimizes the following sum:abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)

(where abs denotes the absolute value)

If there are several possible answers, output the smallest one.

 

Example:

  • For a = [2, 4, 7], the output should be absoluteValuesSumMinimization(a) = 4.

    • for x = 2, the value will be abs(2 - 2) + abs(4 - 2) + abs(7 - 2) = 7.
    • for x = 4, the value will be abs(2 - 4) + abs(4 - 4) + abs(7 - 4) = 5.
    • for x = 7, the value will be abs(2 - 7) + abs(4 - 7) + abs(7 - 7) = 8.

    The lowest possible value is when x = 4, so the answer is 4.

  • For a = [2, 3], the output should be absoluteValuesSumMinimization(a) = 2.

    • for x = 2, the value will be abs(2 - 2) + abs(3 - 2) = 1.
    • for x = 3, the value will be abs(2 - 3) + abs(3 - 3) = 1.

    Because there is a tie, the smallest x between x = 2 and x = 3 is the answer.

-Summary-

1. Set min_sum as the largest integer value in the python to compare each number's sum.

2. for loop 안에서 각 숫자마다의 absolute sum 을 비교하여 기존 min_sum 보다 작을경우 업데이트.

3. for loop 종료후 min_sum 업데이트가 마지막으로 되었던 숫자를 리턴

 

 

문제를 풀고나니, 아래와 같이 중간 값을 구하여 한줄로도 풀수 있는 문제였다. 오늘도 다른 사람의 solution을 보며 또 배운다.

 

return a[(len(a)-1)//2]

 

모든 문제에 대한 저작권은 CodeSignal 회사에 있습니다. [Copyright © 2020 BrainFights Inc. All rights reserved]

https://codesignal.com/

'CodeSignal > Arcade' 카테고리의 다른 글

CodeSignal [34/60] extractEachKth  (0) 2020.05.24
CodeSignal [33/60] stringsRearrangement  (1) 2020.05.23
CodeSignal [31/60] depositProfit  (0) 2020.05.22
CodeSignal [30/60] circleOfNumbers  (0) 2020.05.21
CodeSignal [29/60] chessBoardCellColor  (0) 2020.05.20

댓글