【leetcode】1363. Largest Multiple of Three
题目如下:
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^4
0 <= digits[i] <= 9
- The returning answer must not contain unnecessary leading zeros.
解题思路:首先把digits中的数字分成三组,分别是能被3整除,除以3余数为1以及除以3余数为2。根据数学规律,能被3整除的数字组合在一起也能被3整除,所以能被3整除这一组的所有数字都要选择;接下来再余数3和余数2两组中选择,从这两组各选一个数字可以组成能被3整除的数,或者在同一组中选3个数字也能组成被3整除的数。不妨假设从这两组中选了i个数字进行组间的组合,选完这i个数字后,剩下的两组中再进行组内结合,这里即可求出最大值。因为题目要求的是求出最大值,所以优先选择值较大的数字进行组合即可。
代码如下:
class Solution(object): def largestMultipleOfThree(self, digits): """ :type digits: List[int] :rtype: str """ val_0 = [] val_1 = [] val_2 = [] for i in digits: if i % 3 == 0: val_0.append(i) elif i % 3 == 1: val_1.append(i) else: val_2.append(i) val_1.sort(reverse=True) val_2.sort(reverse=True) # formde by max_l = len(val_1) - len(val_1) % 3 + len(val_2) - len(val_2) % 3 #print max_l inx = 0 for i in range(1,len(val_1)+1): if i > len(val_2): break count = i*2 remain = len(val_1) - i count += (remain - remain%3) remain = len(val_2) - i count += (remain - remain%3) if max_l < count: max_l = count inx = i #print inx,val_1,val_2 val = [] #print val_2[:inx] #print val_1[:inx] val += val_2[:inx] val += val_1[:inx] #print val if len(val_1) > inx: remain = val_1[inx:] last = len(remain) - len(remain)%3 val += remain[:last] if len(val_2) > inx: remain = val_2[inx:] last = len(remain) - len(remain)%3 val += remain[:last] val += val_0 val.sort(reverse=True) res = '' for i in val: res += str(i) if len(res) > 0 and int(res) == 0: return '0' return res