[Geeks for Geeks] Minimum sum

Minimum sum

Given an array Arr of size N such that each element is from the range 0 to 9. Find the minimum possible sum of two numbers formed using the elements of the array. All digits in the given array must be used to form the two numbers.

  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution{
public:
string solve(int arr[], int n) {
string res = "";
int carry = 0;
sort(arr, arr + n);

for(int i = n - 1; i >= 0; i -= 2) {
int sum = carry + arr[i] + (i ? arr[i - 1] : 0);
res += string(1, (sum % 10) + '0');
carry = sum / 10;
}

res += string(1, carry + '0');
while(!res.empty() and res.back() == '0') res.pop_back();

reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/25/PS/GeeksforGeeks/minimum-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.