Check if sum of digits in the left half is divisible by sum of digits in the right half in the largest permutation of N
Given a positive integer N, the task is to maximize the integer N by rearranging the digits and check if the sum of the left half digits is divisible by the sum of the right half digits or not. If found to be true, then print “Yes”. Otherwise, print “No”.
If the number of digits(say D) in the given number N is odd, then consider any of the two possibilities:
- Consider the first (D/2) digit in the left half.
- Consider the first (D/2 + 1) digit in the left half.
Input: N = 43729
Maximum value of N possible by rearranging the digits is 97432.
Sum of digits in the left half = 9 + 7 = 16.
Sum of digits in the right half = 4 + 3 + 2 = 9.
Since, 16 is not divisible by 9, the condition is not satisfied.
Sum of digits in the left half = 9 + 7 + 4 = 20.
Sum of digits in the right half = 3 + 2 = 5.
Since, 20 is divisible by 5, the condition is satisfied.
Input: N = 3746
Approach: The given problem can be solved by sorting the given digits of the number N in descending order maximizing the value of N and then checking for the divisibility of the sum of the left and the right half digits. Follow the steps below to solve the problem:
- Initialize a variable, say D that stores the count of digits of the given number N.
- Store the given number as the string in a variable, say temp.
- Sort the string temp in decreasing order.
- Now check if the sum of the first (D/2) digits is divisible by the sum of the last (D/2) digits, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(log10N)
Auxiliary Space: O(log10N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.