Given many stacks of coins which are arranged adjacently. We need to collect all these coins in the minimum number of steps where in one step we can collect one horizontal line of coins or vertical line of coins and collected coins should be continuous.
Input : height = [2 1 2 5 1] Each value of this array corresponds to the height of stack that is we are given five stack of coins, where in first stack 2 coins are there then in second stack 1 coin is there and so on. Output : 4 We can collect all above coins in 4 steps which are shown in below diagram. Each step is shown by different color. First, we have collected last horizontal line of coins after which stacks remains as [1 0 1 4 0] after that, another horizontal line of coins is collected from stack 3 and 4 then a vertical line from stack 4 and at the end a horizontal line from stack 1. Total steps are 4.
We can solve this problem using divide and conquer method. We can see that it is always beneficial to remove horizontal lines from below. Suppose we are working on stacks from l index to r index in a recursion step, each time we will choose minimum height, remove those many horizontal lines after which stack will be broken into two parts, l to minimum and minimum +1 till r and we will call recursively in those subarrays. Another thing is we can also collect coins using vertical lines so we will choose minimum between the result of recursive calls and (r – l) because using (r – l) vertical lines we can always collect all coins.
As each time we are calling each subarray and finding minimum of that, total time complexity of the solution will be O(N2)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum and minimum of an array using minimum number of comparisons
- Program to count number of set bits in an (big) array
- Count number of occurrences (or frequency) in a sorted array
- Find the minimum element in a sorted and rotated array
- Find the number of zeroes
- Find the missing number in Arithmetic Progression
- Find cubic root of a number
- Minimum difference between adjacent elements of array which contain elements from each row of a matrix
- Allocate minimum number of pages
- Place k elements such that minimum distance is maximized
- Number of days after which tank will become empty
- Find closest number in array
- Smallest number with given sum of digits and sum of square of digits
- Find the Missing Number in a sorted array
- Number of ways to divide a given number as a set of integers in decreasing order