...

/

Solution: Collect Coins in Minimum Steps

Solution: Collect Coins in Minimum Steps

This review discusses the solution of the collect coins in minimum steps challenge in detail.

We'll cover the following...

Solution

We can solve this problem using a divide and conquer technique as follows:

def minimum_steps_recursive(lst, left, right, h):
"""
Helper recursive function to calculate minimum steps to collect coins from the list
:param lst: List of coins stack
:param left: Left sided index of the list
:param right: Right sided index of the list
:param h: Height of the stack
:return: Returns minimum steps to collect coins from the list, otherwise 0
"""
# Base Case: When left is greater or equal to right
if left >= right:
return 0
# loop over the list of heights to get minimum height index
minimum_height = left
for i in range(left, right):
if lst[i] < lst[minimum_height]:
minimum_height = i
# Collecting all vertical line coins which are right - left
# and all the horizontal line coins on both sided segments
return min(right - left, minimum_steps_recursive(lst, left, minimum_height, lst[minimum_height])
+ minimum_steps_recursive(lst, minimum_height + 1, right, lst[minimum_height])
+ lst[minimum_height] - h)
def minimum_steps(lst):
"""
Function which calls the helper function to calculate minimum steps to collect coins from the list
:param lst: List of coins stack
:return: Returns minimum steps to collect coins from the list, otherwise 0
"""
return minimum_steps_recursive(lst, 0, len(lst), 0)
# Driver code to test above function
if __name__ == '__main__':
lst = [2, 1, 2, 5, 1]
print('Minimum number of steps:', minimum_steps(lst))

Explanation

If there are no more coins to collect, we are done in zero steps. Else, we have two options:

a. Either we collect each column individually,

b. Or, since the bottom few rows are guaranteed to be filled contiguously, we pick as many contiguous rows from the bottom as possible, then solve the remaining coins problem recursively. The remaining coins will be in two separate sets from left to minimum_height and minimum_height + 1 to right. So, two ...