You are given a non-negative integer num represented as a string. You can swap any two digits at most once to get the maximum valued number. Return the maximum valued number you can get.
num?num be an empty string, or is it always guaranteed to be at least one digit long?Given we assume:
num is a non-negative integer represented as a string.num is at least 1.num to vector<char> for easier manipulation.n is the number of digits in num.Here is the C++ implementation of the described strategy:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string maximumSwap(string num) {
vector<int> last(10, -1); // to record the last position of digit 0 - 9
// Record the last appearance of each digit
for (int i = 0; i < num.size(); i++) {
last[num[i] - '0'] = i;
}
// Traverse the number to find the first digit that can be swapped to get a larger number
for (int i = 0; i < num.size(); i++) {
for (int d = 9; d > num[i] - '0'; d--) {
if (last[d] > i) {
// A larger digit found, swap
swap(num[i], num[last[d]]);
return num;
}
}
}
// If no swap needed, return original
return num;
}
// Testing the function
int main() {
cout << maximumSwap("2736") << endl; // Expected output: 7236
cout << maximumSwap("9973") << endl; // Expected output: 9973
return 0;
}
last to store the last occurrence of each digit from 0 to 9 in the string.This approach ensures that we maximize the number with the least computational effort possible given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?