-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #115 from Ghanshyam-07/fix/Maximum-swap
Create question.md and solution.cpp
- Loading branch information
Showing
3 changed files
with
69 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters