-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (30 loc) · 802 Bytes
/
Copy pathsolution.cpp
File metadata and controls
36 lines (30 loc) · 802 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution
{
public:
string largestSwap(string &s)
{
int n = s.length();
// Store last occurrence of each digit (0-9)
vector<int> last(10, -1);
for (int i = 0; i < n; i++)
{
last[s[i] - '0'] = i;
}
// Traverse the string
for (int i = 0; i < n; i++)
{
// Check if a larger digit exists later
for (int d = 9; d > s[i] - '0'; d--)
{
if (last[d] > i)
{
// Swap current digit with the larger digit
swap(s[i], s[last[d]]);
return s;
}
}
}
// If no swap improves the number
return s;
}
};