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 bearrayChange(inputArray) = 3
. - For
inputArray = [2, 1, 10, 1]
, the output should bearrayChange(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 signed32
-bit integer type.
- The minimal number of moves needed to obtain a strictly increasing sequence from
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로 관계를 표현하였다.