Skip to content

Commit

Permalink
Create maximum-swap.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 3, 2017
1 parent a1c4dfa commit 8952c85
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions C++/maximum-swap.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Time: O(l), l is the length of the number string
// Space: O(l)

class Solution {
public:
int maximumSwap(int num) {
string digits = to_string(num);
int left = 0, right = 0;
int max_idx = digits.length() - 1;
for (int i = digits.length() - 1; i >= 0; --i) {
if (digits[i] > digits[max_idx]) {
max_idx = i;
} else if (digits[max_idx] > digits[i]) {
left = i;
right = max_idx;
}
}
swap(digits[left], digits[right]);
return stoi(digits);
}
};

0 comments on commit 8952c85

Please sign in to comment.