Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Example 1:
Input: digits = [8,1,9] Output: "981"
Example 2:
Input: digits = [8,6,7,1,0] Output: "8760"
Example 3:
Input: digits = [1] Output: ""
Example 4:
Input: digits = [0,0,0,0,0,0] Output: "0"
Constraints:
1 <= digits.length <= 10^40 <= digits[i] <= 9- The returning answer must not contain unnecessary leading zeros.
Solution in C++:
class Solution {public:
string largestMultipleOfThree(vector<int>& digits) {string s;
vector<int> freq(10, 0);
vector<int> rem1 = {1, 4, 7, 2, 5, 8}; vector<int> rem2 = {2, 5, 8, 1, 3, 7};int sum = 0;
for(int iter = 0; iter < digits.size(); ++iter){sum += digits[iter];
++freq[digits[iter]];
}
while(sum % 3 != 0){ for(int iter = 0; iter < 6; ++iter){ if(sum % 3 == 1 && freq[rem1[iter]]){sum -= rem1[iter];
--freq[rem1[iter]];
break;
} else if(sum % 3 == 2 && freq[rem2[iter]]){sum -= rem2[iter];
--freq[rem2[iter]];
break;
}
}
}
for(int iter = 9; iter >= 0; --iter){ for(int i = 0; i < freq[iter]; ++i){s.push_back(iter + '0');
}
}
return s[0] == '0'? "0":s;
}
};
This comment has been removed by the author.
ReplyDeleteIt looks like there is a typo, should be '1, *4*, 7, 2, 5, 8' right?
ReplyDeleteBoth versions works on leetcode though:)
You're correct Dima. Corrected the same in the post. Thank you
ReplyDeleteRegards,
Sreenivas