VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimal-operations-make-number-magical/

⇱ Minimal operations to make a number magical - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimal operations to make a number magical

Last Updated : 31 Jul, 2022

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. 

Examples : 

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

Approach: 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 ans and at the end return ans.

Below is the implementation of the above approach.  


Output
2

Time complexity : O( 10^6) 
Auxiliary Space : O(1) 

Comment
Article Tags: