I'm stuck in this problem and I would need some help:
Given an array arr
, in each step, 1, 2 or 5 units have to be incremented to all but one item of the array (same amount of units to all of them). The goal is to find the minimum number of steps to all items to be equal.
First example
arr = [1, 1, 5]
1) [1 (+2), 1 (+2), 5] = [3, 3, 5]
2) [3 (+2), 3 (+2), 5] = [5, 5, 5]
Solution: 2 steps
Second example
arr = [2, 2, 3, 7]
1) [2 (+1), 2 (+1), 3, 7 (+1)] = [3, 3, 3, 8]
2) [3 (+5), 3 (+5), 3 (+5), 8] = [8, 8, 8, 8]
Solution: 2 steps
I have tried some things but I'm really stuck.
I consider a base case when all items are already equal. In another case, I try to find all the possible solutions by incrementing 1, 2 and 5 to every item but one in the array:
def equal(arr):
if (allElementsIdentical(arr)):
return 0
min = sys.maxsize
for i in [1, 2, 5]:
for j in range(len(arr)):
#Increment all items by "i", except item at index "j"
newArr = arr.copy()
for k in range(j):
newArr[k] += i
for k in range(j + 1, len(newArr)):
newArr[k] += i
movements = 1 + equal(newArr)
if movements < min:
min = movements
return min
This solution doesn't work because recursion never ends. E.g.
[1, 1, 5] -> [1, 2, 6] -> [1, 3, 7] -> [1, 4, 8] -> [1, 5, 9] -> ...
Is it my initial approach correct? How can I break it down in subproblems properly? How can I get the recurrence relation?
(I'm learning Python, so any comment about the syntax is also appreciated)