-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_MinimumSum.cpp
157 lines (130 loc) · 3.53 KB
/
GFG_MinimumSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
https://practice.geeksforgeeks.org/problems/minimum-sum4058/1/#
Minimum sum
*/
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
string solve(int arr[], int n) {
sort(arr, arr+n);
string n1, n2;
for(int i=0; i<n; i++)
{
if(arr[i] == 0) // TC 3 failed, bec of prefix zero
continue;
if(i%2==0)
n1.push_back(arr[i]+'0');
else
n2.push_back(arr[i] + '0');
}
// cout<<n1<<" "<<n2<<endl;
int i = n1.size()-1;
int j = n2.size()-1;
string ans;
int sum=0, carry=0;
while(i>=0 || j>=0)
{
sum = carry;
if(i>=0)
sum+= n1[i--]-'0';
if(j>=0)
sum+= n2[j--]-'0';
ans += (sum%10)+'0';
carry = sum/10;
}
if(carry)
ans+= carry+'0';
return string(ans.rbegin(), ans.rend());
}
// long long int range out of bound
string solve_2(int arr[], int n)
{
sort(arr, arr+n);
long long int n1=0, n2=0;
for(int i=0; i<n; i++)
{
if(arr[i] == 0) // TC 3 failed, bec of prefix zero
continue;
if(i%2==0)
n1 = n1*10 + arr[i];
else
n2 = n2*10 + arr[i];
}
// int i = n1.size()-1;
// int j = n2.size()-1;
// string ans;
// int sum=0, carry=0;
// while(i>=0 || j>=0)
// {
// sum = carry;
// if(i>=0)
// sum+= n1[i--]-'0';
// if(j>=0)
// sum+= n2[j--]-'0';
// ans += (sum%10)+'0';
// carry = sum/10;
// }
// if(carry)
// ans+= carry+'0';
long long int ans = n1+n2;
// cout<<n1<<" "<<n2<<" "<<ans<<endl;
return to_string(ans);
}
string solve_TLE(int arr[], int n) {
// sort(arr, arr+n);
priority_queue<int, vector<int>, greater<>> pq(arr, arr+n);
string n1, n2;
bool swap = true;
while(!pq.empty())
{
int digit = pq.top(); pq.pop();
if(digit == 0) // TC 3 failed, bec of prefix zero
continue;
if(swap)
n1.push_back(digit+'0');
else
n2.push_back(digit + '0');
swap = !swap;
}
// cout<<n1<<" "<<n2<<endl;
int i = n1.size()-1;
int j = n2.size()-1;
string ans;
int sum=0, carry=0;
while(i>=0 || j>=0)
{
sum = carry;
if(i>=0)
sum+= n1[i--]-'0';
if(j>=0)
sum+= n2[j--]-'0';
ans += (sum%10)+'0';
carry = sum/10;
}
if(carry)
ans+= carry+'0';
return string(ans.rbegin(), ans.rend());
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
Solution ob;
auto ans = ob.solve(arr, n);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends