Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Last active June 1, 2017 21:20
Show Gist options
  • Save tyler-austin/4532db485707aaa08380a87873653eb0 to your computer and use it in GitHub Desktop.
Save tyler-austin/4532db485707aaa08380a87873653eb0 to your computer and use it in GitHub Desktop.
Code Fights - arrayChange

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.

Input/Output

  • [time limit] 4000ms (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.
from typing import List
class ArrayChange:
@classmethod
def array_change(cls, data: List[int]):
increments = 0
prev = data[0] - 1
for d in data:
if prev - d >= 0:
increment = prev - d + 1
increments += increment
d += increment
prev = d
return increments
def arrayChange(data: list):
increments = 0
prev = data[0] - 1
for d in data:
if prev - d >= 0:
increment = prev - d + 1
increments += increment
d += increment
prev = d
return increments
import unittest
from array_change import ArrayChange
class TestArrayChange(unittest.TestCase):
def test_1(self):
input_array = [1, 1, 1]
solution = 3
result = ArrayChange.array_change(input_array)
self.assertEqual(result, solution)
def test_2(self):
input_array = [-1000, 0, -2, 0]
solution = 5
result = ArrayChange.array_change(input_array)
self.assertEqual(result, solution)
def test_3(self):
input_array = [2, 1, 10, 1]
solution = 12
result = ArrayChange.array_change(input_array)
self.assertEqual(result, solution)
def test_4(self):
input_array = [2, 3, 3, 5, 5, 5, 4, 12, 12, 10, 15]
solution = 13
result = ArrayChange.array_change(input_array)
self.assertEqual(result, solution)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment