Skip to content

Commit

Permalink
Merge pull request #115 from Ghanshyam-07/fix/Maximum-swap
Browse files Browse the repository at this point in the history
Create question.md and solution.cpp
  • Loading branch information
Kushal997-das authored Oct 30, 2024
2 parents 909e44e + 5ea5ef1 commit a6bd609
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
21 changes: 21 additions & 0 deletions Beginner Level πŸ“/Maximum Swap/question.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
### 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
46 changes: 46 additions & 0 deletions Beginner Level πŸ“/Maximum Swap/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // For the swap function

using namespace std;

class Solution {
public:
int maximumSwap(int num) {
string str = to_string(num);
vector<int> last(10, -1);

// Record the last occurrence of each digit
for (int i = 0; i < str.length(); i++) {
last[str[i] - '0'] = i;
}

// Try to find the first place to swap for maximizing the number
for (int i = 0; i < str.length(); i++) {
for (int d = 9; d > str[i] - '0'; d--) {
if (last[d] > i) {
swap(str[i], str[last[d]]);
return stoi(str);
}
}
}

return num;
}
};

int main() {
Solution solution;
int num;

// Take input from the user
cout << "Enter a number: ";
cin >> num;

// Call the function and display the result
int result = solution.maximumSwap(num);
cout << "Maximum number after swap: " << result << endl;

return 0;
}
3 changes: 2 additions & 1 deletion Beginner Level πŸ“/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
{
"name": "Ghanshyam Saini",
"githubUsername": "Ghanshyam07"
"githubUsername": "Ghanshyam-07"
},
{
"name": "Neyna Nayak",
Expand All @@ -61,6 +61,7 @@

"name": "Dhara Bindal",
"githubUsername": "bindaldhara"

}
{
"name": "Avid Coder",
Expand Down

0 comments on commit a6bd609

Please sign in to comment.