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:
Press + to interact
#include <iostream>using namespace std;// returns minimum of two numbersint min2(int a, int b){return a < b ? a : b;}/*Utility method, called recursively to collectcoins from `l` to `r` using the height arrayassuming that h height has already been collected*/int minimumStepsUtil(int l, int r, int h, int height[]) {// base condition: all coins already collectedif (l >= r)return 0;// find minimum height indexint m = l;for (int i = l; i < r; i++)if (height[i] < height[m])m = i;/*Calculate min steps by:a) collecting all vertical line coins(total r - l)b) collecting all lower horizontal line coinsrecursively on left and right segments*/return min2(r - l,minimumStepsUtil(l, m, height[m], height) +minimumStepsUtil(m + 1, r, height[m], height) +height[m] - h);}/*calls the recursive utility functionand returns the minimum number of stepsusing height array*/int minimumSteps(int height[], int N) {return minimumStepsUtil(0, N, 0, height);}// Testing minimumSteps() methodint main() {int height[] = { 2, 1, 2, 5, 1 };int N = sizeof(height) / sizeof(int);cout << minimumSteps(height, N) << endl;return 0;}
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 since the bottom rows are guaranteed to be filled.
Let’s suppose that we are working on coin stacks from left stack l
to right stack r
in ...