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 rightif left >= right:return 0# loop over the list of heights to get minimum height indexminimum_height = leftfor 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 segmentsreturn 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 functionif __name__ == '__main__':lst = [2, 1, 2, 5, 1]print('Minimum number of steps:', minimum_steps(lst))
Explanation
If there are ...
Access this course and 1400+ top-rated courses and projects.