2024-10-17 Daily Challenge
Today I have done leetcode's October LeetCoding Challenge with cpp
.
October LeetCoding Challenge 17
Description
Maximum Swap
You are given an integer num
. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973 Output: 9973 Explanation: No swap.
Constraints:
0 <= num <= 108
Solution
class Solution {
public:
int maximumSwap(int num) {
using pci = pair<char, int>;
priority_queue<pci> pq;
string n = to_string(num);
pair<int, int> targetSwap = {-1, -1};
for(int i = n.length() - 1; i >= 0; --i) {
if(pq.size() && pq.top().first > n[i]) {
targetSwap = {i, pq.top().second};
}
pq.push({n[i], i});
}
if(targetSwap.first != -1) {
swap(n[targetSwap.first], n[targetSwap.second]);
}
return stoi(n);
}
};