File tree Expand file tree Collapse file tree 3 files changed +69
-1
lines changed
Expand file tree Collapse file tree 3 files changed +69
-1
lines changed Original file line number Diff line number Diff line change 1+ ### Maximum Swap
2+
3+ You are given an integer num. You can swap two digits at most once to get the maximum valued number.
4+ Return the maximum valued number you can get.
5+
6+ ### Example 1:
7+
8+ Input: num = 2736
9+ Output: 7236
10+ Explanation: Swap the number 2 and the number 7.
11+
12+ ### Example 2:
13+
14+ Input: num = 9973
15+ Output: 9973
16+ Explanation: No swap.
17+
18+
19+ ## Constraints:
20+
21+ - 0 <= num <= 108
Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ #include < string>
3+ #include < vector>
4+ #include < algorithm> // For the swap function
5+
6+ using namespace std ;
7+
8+ class Solution {
9+ public:
10+ int maximumSwap (int num) {
11+ string str = to_string (num);
12+ vector<int > last (10 , -1 );
13+
14+ // Record the last occurrence of each digit
15+ for (int i = 0 ; i < str.length (); i++) {
16+ last[str[i] - ' 0' ] = i;
17+ }
18+
19+ // Try to find the first place to swap for maximizing the number
20+ for (int i = 0 ; i < str.length (); i++) {
21+ for (int d = 9 ; d > str[i] - ' 0' ; d--) {
22+ if (last[d] > i) {
23+ swap (str[i], str[last[d]]);
24+ return stoi (str);
25+ }
26+ }
27+ }
28+
29+ return num;
30+ }
31+ };
32+
33+ int main () {
34+ Solution solution;
35+ int num;
36+
37+ // Take input from the user
38+ cout << " Enter a number: " ;
39+ cin >> num;
40+
41+ // Call the function and display the result
42+ int result = solution.maximumSwap (num);
43+ cout << " Maximum number after swap: " << result << endl;
44+
45+ return 0 ;
46+ }
Original file line number Diff line number Diff line change 4444 },
4545 {
4646 "name" : " Ghanshyam Saini" ,
47- "githubUsername" : " Ghanshyam07 "
47+ "githubUsername" : " Ghanshyam-07 "
4848 },
4949 {
5050 "name" : " Neyna Nayak" ,
6161
6262 "name" : " Dhara Bindal" ,
6363 "githubUsername" : " bindaldhara"
64+
6465 }
6566 {
6667 "name" : " Avid Coder" ,
You canβt perform that action at this time.
0 commit comments