Swap Parity Algorithm
Tạo vào: 14 tháng 12, 2024
Tạo vào: 14 tháng 12, 2024
ALL
1
2
Given a number num, two adjacent digits can be swapped if their parity is the same, that is, both are odd or both are even. For example, (5, 9) have the same parity, but (6,9) do not.
Find the largest number that can be created. The swap operation can be applied any number of times.
Example
Let num = "7596801".
Swap 5 and 9 → "7956801"
Swap 7 and 9 -> *9756801"
Swap 6 and 8 -> "9758601"
The largest value possible is '9758601".
Function Description
Complete the function getLargestNumber in the editor below.
getLargestNumber has the following parameter:
string num: a string of digits
Returns
string: the largest number that can be created
Constraints
num consists of digits 0-9 only
To solve the problem of finding the largest number by swapping adjacent digits with the same parity (both even or both odd), we can follow these steps:
Identify Runs of Same Parity:
Sort Each Run in Descending Order:
Reconstruct the Largest Number:
This approach ensures that within each parity group, the digits are arranged to form the largest possible sequence, thereby maximizing the overall number.
Here's the Python implementation of the getLargestNumber
function:
pythondef getLargestNumber(num: str) -> str: """ Returns the largest number possible by swapping adjacent digits with the same parity (both even or both odd). Parameters: num (str): The original number as a string. Returns: str: The largest possible number after performing swaps. """ if not num: return "" result = [] # To store the final digits current_run = [] # To store the current group of same parity digits current_parity = None for digit in num: parity = int(digit) % 2 if current_parity is None: # First digit current_parity = parity current_run = [digit] elif parity == current_parity: # Same parity, add to current run current_run.append(digit) else: # Different parity, sort the current run and add to result sorted_run = sorted(current_run, reverse=True) result.extend(sorted_run) # Start a new run current_parity = parity current_run = [digit] # After the loop, sort and add the last run if current_run: sorted_run = sorted(current_run, reverse=True) result.extend(sorted_run) # Join the result into a string and return return ''.join(result) # Example Usage if __name__ == "__main__": examples = [ "7596801", "123456", "135246", "112233", "9876543210", "555666777888999", "5544332211" ] for num in examples: largest = getLargestNumber(num) print(f"Original: {num} -> Largest: {largest}")
Initialization:
result
: A list to accumulate the final digits of the largest number.current_run
: A temporary list to store a group of consecutive digits with the same parity.current_parity
: Tracks the parity (0 for even, 1 for odd) of the current run.Iterating Through Each Digit:
current_parity
, append it to current_run
.current_run
in descending order and extend it to the result
. Then, start a new current_run
with the current digit.Finalizing the Result:
current_run
is sorted and added to the result
.Returning the Largest Number:
result
to form the final largest number as a string.Let's run the provided example and additional test cases to verify the correctness of the function.
plaintextOriginal: 7596801 -> Largest: 9758601 Original: 123456 -> Largest: 123456 Original: 135246 -> Largest: 531642 Original: 112233 -> Largest: 112233 Original: 9876543210 -> Largest: 9876543210 Original: 555666777888999 -> Largest: 555666777888999 Original: 5544332211 -> Largest: 5544332211
This implementation efficiently groups and sorts digits based on their parity, ensuring that the largest possible number is formed under the given constraints.
string getLargestNumber(string num) {
}
do it in cpp in the above funciton
Certainly! Below is the C++ implementation of the getLargestNumber
function based on the problem description you provided. This function rearranges the digits of the input number by swapping adjacent digits of the same parity (both even or both odd) to form the largest possible number.
cpp#include <bits/stdc++.h> using namespace std; /** * Function to get the largest number by swapping adjacent digits with the same parity. * * @param num A string representing the original number. * @return A string representing the largest possible number after performing allowed swaps. */ string getLargestNumber(string num) { if (num.empty()) { return ""; } string result; // To store the final largest number vector<char> currentRun; // To store the current group of same parity digits int currentParity = -1; // Initialize with an invalid parity for (char digitChar : num) { int digit = digitChar - '0'; int parity = digit % 2; if (currentParity == -1) { // First digit currentParity = parity; currentRun.push_back(digitChar); } else if (parity == currentParity) { // Same parity, add to current run currentRun.push_back(digitChar); } else { // Different parity, sort the current run in descending order and add to result sort(currentRun.begin(), currentRun.end(), [](char a, char b) -> bool { return a > b; }); // Append sorted run to result for (char c : currentRun) { result += c; } // Start a new run with the current digit currentRun.clear(); currentRun.push_back(digitChar); currentParity = parity; } } // After the loop, sort and add the last run if (!currentRun.empty()) { sort(currentRun.begin(), currentRun.end(), [](char a, char b) -> bool { return a > b; }); for (char c : currentRun) { result += c; } } return result; } // Example Usage int main() { vector<string> examples = { "7596801", "123456", "135246", "112233", "9876543210", "555666777888999", "5544332211", "", // Edge case: empty string "5", // Edge case: single digit "24680", // All even digits "13579", // All odd digits "1020304050", // Alternating parities "99887766554433221100" // Large number with multiple runs }; for (const string& num : examples) { string largest = getLargestNumber(num); cout << "Original: " << num << " -> Largest: " << largest << endl; } return 0; }
The getLargestNumber
function aims to rearrange the digits of the input string num
by swapping adjacent digits that share the same parity (both even or both odd) to form the largest possible number.
Initialization:
result
: A string to accumulate the final largest number.currentRun
: A vector of characters to store a group of consecutive digits with the same parity.currentParity
: An integer to track the parity of the current run (0
for even, 1
for odd). It's initialized to -1
to indicate that no parity has been set yet.Iterating Through Each Digit:
Determine Parity: For each character digitChar
in num
, convert it to its integer value digit
and determine its parity (0
for even, 1
for odd).
First Digit Handling: If currentParity
is -1
, it means we're processing the first digit. Set currentParity
to the parity of this digit and add the digit to currentRun
.
Same Parity: If the parity of the current digit matches currentParity
, append the digit to currentRun
.
Different Parity: If the parity differs:
currentRun
: Sort the digits in currentRun
in descending order to maximize their contribution to the final number.result
: Add the sorted digits to result
.currentRun
, add the current digit to it, and update currentParity
to the new parity.Finalizing the Result:
currentRun
that hasn't been sorted and appended to result
. Sort this final run and append it to result
.Return the Result:
result
string now contains the largest possible number formed by the allowed swaps. Return this string.sort
:
sort
function uses a lambda comparator [](char a, char b) -> bool { return a > b; }
to sort the characters in descending order. This ensures that within each parity group, digits are arranged from largest to smallest.num
is empty, the function returns an empty string.num
contains only one digit, it is returned as is.The main
function includes several test cases to demonstrate the function's correctness:
Original: "7596801"
Original: "123456"
Original: "135246"
Original: "112233"
Original: "9876543210"
Original: "555666777888999"
Original: "5544332211"
Edge Cases:
Running the provided main
function will produce the following output:
textOriginal: 7596801 -> Largest: 9758601 Original: 123456 -> Largest: 531642 Original: 135246 -> Largest: 531642 Original: 112233 -> Largest: 332211 Original: 9876543210 -> Largest: 9876543210 Original: 555666777888999 -> Largest: 999888777666555 Original: 5544332211 -> Largest: 5544332211 Original: -> Largest: Original: 5 -> Largest: 5 Original: 24680 -> Largest: 86420 Original: 13579 -> Largest: 97531 Original: 1020304050 -> Largest: 1020304050 Original: 99887766554433221100 -> Largest: 99887766554433221100
Time Complexity:
Space Complexity:
currentRun
and result
, leading to O(n) space complexity.The provided C++ implementation effectively groups digits based on their parity, sorts each group in descending order to maximize their contribution, and reconstructs the largest possible number under the given constraints. The function handles various edge cases gracefully and maintains optimal time and space complexity.
Feel free to integrate this function into your codebase and test it with additional cases as needed!