Skip to content

Commit a6bd609

Browse files
Merge pull request #115 from Ghanshyam-07/fix/Maximum-swap
Create question.md and solution.cpp
2 parents 909e44e + 5ea5ef1 commit a6bd609

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}

β€ŽBeginner Level πŸ“/data.jsonβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
},
4545
{
4646
"name": "Ghanshyam Saini",
47-
"githubUsername": "Ghanshyam07"
47+
"githubUsername": "Ghanshyam-07"
4848
},
4949
{
5050
"name": "Neyna Nayak",
@@ -61,6 +61,7 @@
6161

6262
"name": "Dhara Bindal",
6363
"githubUsername": "bindaldhara"
64+
6465
}
6566
{
6667
"name": "Avid Coder",

0 commit comments

Comments
Β (0)