티스토리 뷰

Codesignal

code signal - 17. arrayChange

터보건 2020. 2. 19. 15:26

Question

You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.


Example

  • For inputArray = [1, 1, 1], the output should be arrayChange(inputArray) = 3.
  • For inputArray = [2, 1, 10, 1], the output should be arrayChange(inputArray) = 12.

Input/Output

  • [execution time limit] 4 seconds (py3)

  • [input] array.integer inputArray

    Guaranteed constraints: 3 ≤ inputArray.length ≤ 105, -105 ≤ inputArray[i] ≤ 105.

  • [output] integer

    • The minimal number of moves needed to obtain a strictly increasing sequence from inputArray. It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type.

MY_ANSWER

def arrayChange(inputArray):
    letter = 0

    for i in range(len(inputArray)-1):
        if inputArray[i] >= inputArray[i+1]:
            letter += (inputArray[i]+1 - inputArray[i+1])
            inputArray[i+1] = inputArray[i]+1        
        else:
            inputArray[i]
    
    return letter
  • Input list가 들어왔을 때 i 번째 원소가 i + 1번째 원소보다 클 경우, i + 1번째 원소를 i번째 원소보다 크도록 만들어 주어야한다. 그 때 얼마만큼 원소에 더해줄 것 인지가 return값으로 나와야 한다.
  • inputArray = [2, 1, 10, 1] 일 경우 inputArray = [2, 3, 10, 11]가 되는 것이 가장 이상적일 것이다. 이 때의 return값은 2 + 10 = 12
  • i와 i+1 번째의 원소를 비교한 다음, i 번째 원소가 크면 i+1가 i번째보다 1이상 크도록 만들어준 뒤 차이를 letter를 곳에 더해주어 return을 해준다.

Best_ANSWER

def arrayChange(inputArray):
    a = 0
    for i in range(1, len(inputArray)):
        if inputArray[i] <= inputArray[i - 1]:
            f = (inputArray[i - 1] - inputArray[i]) + 1
            inputArray[i] = inputArray[i - 1] + 1
            a += f
    return a
  • 조금 비슷하지만 다른 code, i, i - 1로 관계를 표현하였다.

 

'Codesignal' 카테고리의 다른 글

code signal - 19. areEquallyStrong  (0) 2020.02.19
code signal - 18. palindromeRearranging  (0) 2020.02.19
code signal - 16. Are similar?  (0) 2020.02.16
code signal - 15. Add Border  (0) 2020.02.16
code signal - 14. alternatingSums  (0) 2020.02.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함