Given a 3 digit integer n divide the number into a pair of two numbers such that their sum is minimum.
For example if n is 475 then we can divide it into 45 and 7 the sum will be minimum that will be 52.
Examples :
Input : n=139 Output : 22 Explanation : The smallest pair of numbers we can divide it into is 13 and 9 which gives us the sum as 22 The other pairs formed will always give the sum more than 22 that is if we consider the pair 91 and 3 the sum will be 94 which is more than 22 Input : n=451 Output : 19 Explanation : The smallest pair of numbers we can divide it into is 15 and 4 which gives us the sum as 19. The other pairs formed will always give the sum more than 19 that is if we consider the pair 45 and 1 the sum will be 46 which is more than 19. Similarly if we consider 41 and 5 this will also give us the sum as 46. Hence 19 will be the minimum possible sum
Approach :
The task can be solved using some observations.
It can be observed that the minimum sum of the pair exists when we sort the digits of n in increasing order and form one number from the first two digits and the second number from the third digit.
Implementation :
#include <bits/stdc++.h>
using namespace std;
int minSumPossible(int n)
{
// treating the number as string to get the digits
// directly
string s = to_string(n);
// sort the number as string
sort(s.begin(), s.end());
// converting the char to int back as digits
int s0 = s[0] - '0';
int s1 = s[1] - '0';
int s2 = s[2] - '0';
// n1 will be the number formed by the two smaller
// digits
int n1 = s0 * 10 + s1;
// n2 will be the number formed by the third digit
int n2 = s2;
// sum of n1 and n2
int sum = n1 + n2;
return sum;
}
int main()
{
int n = 451;
cout << minSumPossible(n) << endl;
}
Output : 19