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 by implementing the divide and conquer algorithm as follows:
Press + to interact
class CollectCoins {// Utility method, called recursively to collect coins from `l` to `r` using the height array assuming that h height has already been collectedpublic static int minimumStepsUtil(int left, int right, int h, int height[]) {if (left >= right) // base case: all coins already collectedreturn 0;int min = left;for (int i = left; i < right; i++) // finding minimum height index{if (height[i] < height[min])min = i;}return Math.min(right - left, minimumStepsUtil(left, min, height[min], height) +minimumStepsUtil(min + 1, right, height[min], height) + height[min] - h);}// calls the recursive utility function and returns the minimum number of steps using height arraypublic static int minimumSteps(int height[], int N) {return minimumStepsUtil(0, N, 0, height);}// driver program to test the above functionspublic static void main(String args[]) {int[][] inputs = {{3, 1, 1, 5, 1},{ 4, 2, 1, 5, 2 }}; // you can always play around with these input values to see changing outputsfor (int i = 0; i < inputs.length; i++) {System.out.println("Min Steps for " + Arrays.toString(inputs[i]) + " ---> " + minimumSteps(inputs[i], inputs[i].length));}}}
Explanation
If we start horizontally from the bottom, we can get rid of the minimum height coin rows, while collecting the maximum possible number of coins because the bottom rows are guaranteed to be filled.
Suppose that we are working on the coin stacks from the left stack, say left
, to the right stack, right
, in each recursion step.
-
Choose the minimum height index
min
. Removemin
horizontal lines after which the stack will be broken into ...