-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day228.cpp
80 lines (56 loc) · 1.53 KB
/
Day228.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
#include <bits/stdc++.h>
using namespace std;
/*
This problem was asked by Twitter.
Given a list of numbers, create an algorithm that arranges them in order to form the largest possible integer. For example, given [10, 7, 76, 415], you should return 77641510.
*/
vector<int> arr;
string toString(int a){
string res;
stringstream ss;
ss << a;
ss >> res;
return res;
}
bool comp(int a, int b){
string A = toString(a);
string B = toString(b);
for(int i=0; i<min(A.size(), B.size()); i++)
if(A[i]!=B[i])
return A[i]>B[i];
return A.size()<B.size();
}
int solve(){
/*
MEDIUM
Solution:
We have a greedy approach to this problem. Just sort the array prioritizing the bigger digits from the left.
If the comparation by digits it's over and the number A is bigger (in number of digits) than the number B, prioritize number B.
Then, just accumulate the numbers in the order of the resulting array.
Example of input:
4
10 7 76 415
Example of output:
77641510
Complexity: O(N*log(N) + N).
*/
sort(arr.begin(), arr.end(), comp);
int newNumber = 0;
for(int i=0; i<arr.size(); i++){
if(i==0)
newNumber+=arr[i];
else{
newNumber*=pow(10, (toString(arr[i]).size()));
newNumber+=arr[i];
}
}
return newNumber;
}
int main () {
int n;
cin >> n;
arr.resize(n);
for(int i=0; i<n; i++) cin >> arr[i];
cout << solve() << endl;
return 0;
}