Leetcode 2160. Minimum Sum of Four Digit Number After Splitting Digits
You are given a positive integer num consisting of exactly four digits. You need to split num into two new integers new1 and new2 by rearranging its digits. The task is to return the minimum possible sum of new1 and new2.
Example:
num = 293252The possible pairs of new1 and new2 after rearranging the digits can be (29, 23) leading to the minimum sum 52.
num have leading zeros?
num is a positive integer with exactly four digits (1000 to 9999).new1 and new2 need to be non-zero integers?
new1 and new2 should be non-zero integers formed by using exactly two of the digits from num.new1 and new2?
num must be used exactly once.To achieve the minimum sum:
num.Steps:
num.Here’s the implementation of the solution strategy in C++:
#include <iostream>
#include <vector>
#include <algorithm>
int minimumSum(int num) {
// Extract digits
std::vector<int> digits;
while (num > 0) {
digits.push_back(num % 10);
num /= 10;
}
// Sort the digits
std::sort(digits.begin(), digits.end());
// Form two numbers such that their sum is minimized
int new1 = digits[0] * 10 + digits[2];
int new2 = digits[1] * 10 + digits[3];
return new1 + new2;
}
// Driver code to test the function
int main() {
int num = 2932;
std::cout << "Minimum sum: " << minimumSum(num) << std::endl; // Output should be 52
return 0;
}
O(1) since the number has a fixed number of digits (4).O(4 log 4), but as this is a constant size, it simplifies to O(1) in practical terms.O(1).Overall, the time complexity is O(1) considering the constraints.
This ensures that the solution is optimal and efficient for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?