diff --git a/Build Lowest Number by Removing n digits from a given number b/Build Lowest Number by Removing n digits from a given number new file mode 100644 index 0000000..a7e391d --- /dev/null +++ b/Build Lowest Number by Removing n digits from a given number @@ -0,0 +1,46 @@ +// C++ program for the above approach + +#include +using namespace std; + +string removeKdigits(string num, int k) +{ + int n = num.size(); + stack mystack; + // Store the final string in stack + for (char c : num) { + while (!mystack.empty() && k > 0 + && mystack.top() > c) { + mystack.pop(); + k -= 1; + } + + if (!mystack.empty() || c != '0'){ + mystack.push(c); + } + } + + // Now remove the largest values from the top of the + // stack + while (!mystack.empty() && k--) + mystack.pop(); + if (mystack.empty()) + return "0"; + + // Now retrieve the number from stack into a string + // (reusing num) + while (!mystack.empty()) { + num[n - 1] = mystack.top(); + mystack.pop(); + n -= 1; + } + return num.substr(n); +} + +int main() +{ + string str = "765028321"; + int k = 5; + cout << removeKdigits(str, k); + return 0; +}