Given a 6 digit number, calculate the minimum number of digits that needs to be replaced in order to make the number magical. The number is considered magical if the sum of first three digits equals to the sum of last three digits. In one operation, we can choose a digit at any position and replace it with any arbitrary digit.
Input: 123456 Output: 2 Explanation : Replace 4 with 0 and 5 with 0, then number = 123006, where 1 + 2 + 3 = 0 + 0 + 6, hence number of replacements done = 2 Input: 111000 Output: 1 Explanation: Replace 0 with 3, then number = 111030, where 1 + 1 + 1 = 0 + 3 + 0, hence number of replacements done = 1
The best approach will be to check with all the magical numbers and the number of replacements needed. Run a loop that generates all 6 digit numbers. Check if that number is magical, if it is then simply calculate the number of replacements needs to be done and compare with the ans, if it is smaller then make it the the ans and at the end return ans.
Below is the implementation of the above approach.
Time complexity : O( 10^6)
Auxiliary Space : O(1)
This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Replace minimal number of characters to make all characters pair wise distinct
- Make a lexicographically smallest palindrome with minimal changes
- Minimum number of given operations required to make two strings equal
- Minimum number of operations required to make two strings equal
- Operations required to make the string empty
- Count of operations to make a binary string"ab" free
- Minimum operations to make frequency of all characters equal K
- Minimum move to end operations to make all strings equal
- Minimum operations required to make the string satisfy the given condition
- Reduce N to 1 with minimum number of given operations
- Maximum number of given operations to remove the entire string
- Count the number of carry operations required to add two numbers
- Minimal moves to form a string by adding characters or appending string itself
- Find the maximum difference after applying the given operations two times on a number
- Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B