For example, if the input number is 24635, the least number is 23 after deleting any 3 digits.
It\'s not the same as taking the two smalles
The idea is based on the fact that a character among first (n+1) characters must be there in resultant number. So we pick the smallest of first (n+1) digits and put it in result, and recur for remaining characters. Below is complete algorithm.
Initialize result as empty string i.e. res = ""
buildLowestNumber(str, n, res)
1) If n == 0, then there is nothing to remove. Append the whole 'str' to 'res' and return
2) Let 'len' be length of 'str'. If 'len' is smaller or equal to n, then everything can be removed. Append nothing to 'res' and return
3) Find the smallest character among first (n+1) characters of 'str'. Let the index of smallest character be minIndex. Append 'str[minIndex]' to 'res' and recur for substring after minIndex and for n = n-minIndex
buildLowestNumber(str[minIndex+1..len-1], n-minIndex).
#include
using namespace std;
// A recursive function that removes 'n' characters from 'str'
// to store the smallest possible number in 'res'
void buildLowestNumberRec(string str, int n, string &res)
{
// If there are 0 characters to remove from str,
// append everything to result
if (n == 0)
{
res.append(str);
return;
}
int len = str.length();
// If there are more characters to remove than string
// length, then append nothing to result
if (len <= n)
return;
// Find the smallest character among first (n+1) characters
// of str.
int minIndex = 0;
for (int i = 1; i<=n ; i++)
if (str[i] < str[minIndex])
minIndex = i;
// Append the smallest character to result
res.push_back(str[minIndex]);
// substring starting from minIndex+1 to str.length() - 1.
string new_str = str.substr(minIndex+1, len-minIndex);
// Recur for the above substring and n equals to n-minIndex
buildLowestNumberRec(new_str, n-minIndex, res);
}
// A wrapper over buildLowestNumberRec()
string buildLowestNumber(string str, int n)
{
string res = "";
// Note that result is passed by reference
buildLowestNumberRec(str, n, res);
return res;
}
// Driver program to test above function
int main()
{
string str = "121198";
int n = 2;
cout << buildLowestNumber(str, n);
return 0;
}