-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1363. Largest Multiple of Three.cpp
54 lines (46 loc) · 1.65 KB
/
1363. Largest Multiple of Three.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
class Solution {
public:
void findIndices(vector<int>&digits,int& first,int& second,int rem){
for(int i=0;i<digits.size();i++){
if(digits[i] % 3 == rem){
if(first == -1) first = i;
else{
second = i;
break;
}
}
}
}
string largestMultipleOfThree(vector<int>& digits) {
int n = digits.size();
sort(digits.begin(),digits.end());
int sum = accumulate(digits.begin(),digits.end(),0);
string ans = "";
if(sum % 3 != 0){
int same = (sum % 3);
int other = (same == 1 ? 2 : 1);
bool isIdealFound = false;
int first = -1,second = -1;
findIndices(digits,first,second,same);
if(first != -1){
//if minimum elements with same remender found just remove this
isIdealFound = true;
digits[first] = -1;
}
if(!isIdealFound){
//if same remainder element not found look for two with other rem and remove
findIndices(digits,first,second,other);
if(second == -1) return "";
digits[first] = -1;
digits[second] = -1;
}
}
//calculating answer
for(int i=n-1;i>=0;i--){
if(digits[i] != -1) ans.push_back(digits[i] + '0');
}
if(ans.size() == 0) return "";
else if(ans[0] == '0') return "0";
return ans;
}
};