You are given a lock which is made up of n-different circular rings and each ring has 0-9 digit printed serially on it. Initially all n-rings together show a n-digit integer but there is particular code only which can open the lock. You can rotate each ring any number of time in either direction. You have to find the minimum number of rotation done on rings of lock to open the lock.
Input : Input = 2345, Unlock code = 5432 Output : Rotations required = 8 Explanation : 1st ring is rotated thrice as 2->3->4->5 2nd ring is rotated once as 3->4 3rd ring is rotated once as 4->3 4th ring is rotated thrice as 5->4->3->2 Input : Input = 1919, Unlock code = 0000 Output : Rotations required = 4 Explanation : 1st ring is rotated once as 1->0 2nd ring is rotated once as 9->0 3rd ring is rotated once as 1->0 4th ring is rotated once as 9->0
For a single ring we can rotate it in any of two direction forward or backward as:
But we are concerned with minimum number of rotation required so we should choose min (abs(a-b), 10-abs(a-b)) as a-b denotes the number of forward rotation and 10-abs(a-b) denotes the number of backward rotation for a ring to rotate from a to b. Further we have to find minimum number for each ring that is for each digit. So starting from right most digit we can easily the find minimum number of rotation required for each ring and end up at left most digit.
Minimum Rotation = 12
This article is contributed by Shivam Pradhan (anuj_charm). 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.
- Find if k bookings possible with given arrival and departure times
- Minimum cost to process m tasks where switching costs
- Maximum trains for which stoppage can be provided
- Lexicographically largest subsequence such that every character occurs at least k times
- Policemen catch thieves
- Correctness of Greedy Algorithms
- Job Scheduling with two jobs allowed at a time
- Check if the door is open or closed
- Paper Cut into Minimum Number of Squares
- Minimum Cost to cut a board into squares
- Shortest Superstring Problem
- K Centers Problem | Set 1 (Greedy Approximate Algorithm)
- Greedy Algorithm for Egyptian Fraction
- Minimize Cash Flow among a given set of friends who have borrowed money from each other
- Minimum Number of Platforms Required for a Railway/Bus Station