Leetcode 2578. Split With Minimum Sum
You are given a positive integer num
consisting of exactly n
digits. You should split the number into two new integers num1
and num2
such that:
num1
and num2
are non-negative integers.num1
and num2's
digits results in num
.num1
and num2
must not contain any leading zeros.The task is to minimize the sum of num1
and num2
.
Example:
Input: num = 4325
Output: 59
Explanation: num1 is 4 and num2 is 325, and their sum is 4 + 55 = 59.
Input: num = 687
Output: 75
Explanation: num1 is 6 and num2 is 87, and their sum is 6 + 69 = 75.
num
can have?
num
will have at least 2 digits.num
?
num1
and num2
be equal to zero?
num1
and num2
cannot have leading zeros and must be valid non-negative integers when split.To minimize the sum of the resulting numbers from the split, the lower digits should be distributed into the smaller number and the higher digits should focus on creating a larger number. Sorting the digits will help in arranging them optimally.
Here is a concise implementation of the above strategy in C++:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int splitWithMinimumSum(int num) {
string numStr = to_string(num);
sort(numStr.begin(), numStr.end());
string num1, num2;
for (int i = 0; i < numStr.size(); ++i) {
if (i % 2 == 0)
num1 += numStr[i];
else
num2 += numStr[i];
}
// Convert the resulting strings back to integers
int num1Int = num1.empty() ? 0 : stoi(num1);
int num2Int = num2.empty() ? 0 : stoi(num2);
return num1Int + num2Int;
}
int main() {
// Example usage:
int num = 4325;
cout << "Minimum sum after split: " << splitWithMinimumSum(num) << endl; // Output: 59
num = 687;
cout << "Minimum sum after split: " << splitWithMinimumSum(num) << endl; // Output: 75
return 0;
}
The main operations are:
Thus, the overall time complexity is O(n log n)
.
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?