Maximum Swap - Array - Medium - LeetCode
💻 coding

Maximum Swap - Array - Medium - LeetCode

1 min read 123 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves swapping two digits in a non-negative integer to achieve the maximum possible value.
  • 2The solution uses an array to track the last occurrence of each digit for efficient swapping.
  • 3The algorithm operates with a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves swapping two digits in a non-negative integer to achieve the maximum possible value."

Maximum Swap - Array - Medium - LeetCode

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: 9973 Output: 9973 Explanation: No swap. Note: The given number is in the range [0, 108]

public class Solution {
 public int MaximumSwap(int num) {
 
 var digits = num.ToString().ToCharArray();
 var buckets = new int[10];
 for(int i=0;i<digits.Length;i++){
 buckets[digits[i]-'0'] = i;
 }
 
 for(int i=0; i< digits.Length; i++){
 for(int j=9;j > digits[i] - '0'; j--){
 if(buckets[j] > i){
 char tmp = digits[i];
 digits[i] = digits[buckets[j]];
 digits[buckets[j]]=tmp;
 return int.Parse(new string(digits));
 }
 }
 }
 return num;
 }
}

Time Complexity: O(n) Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 4 March 2021 · 1 min read · 123 words

Part of AskGif Blog · coding

You might also like

Maximum Swap - Array - Medium - LeetCode | AskGif Blog