观察:如果你能得到一个能被3整除的数字,你最多需要删除2个数字,以保持最优解。
一个简单的O(n^2)
解决方案是检查所有删除 1 个数字的可能性,如果没有一个有效,则检查所有对(有O(n^2)
那些)。
EDIT:
O(n)
解决方案:创建3个桶 -bucket1
, bucket2
, bucket0
。每个都表示数字的模 3 值。忽略bucket0
在下一个算法中。
令数组的总和为sum
.
If sum % 3 ==0: we are done.
else if sum % 3 == 1:
if there is a number in bucket1 - chose the minimal
else: take 2 minimals from bucket 2
else if sum % 3 == 2
if there is a number in bucket2 - chose the minimal
else: take 2 minimals from bucket1
注意:您实际上并不需要存储桶来实现O(1)
空间 - 您只需要 2 个最小值bucket1
and bucket2
,因为它是我们实际使用的这些桶中的唯一数字。
Example:
arr = { 3, 4, 0, 1, 5 }
bucket0 = {3,0} ; bucket1 = {4,1} bucket2 = { 5 }
sum = 13 ; sum %3 = 1
bucket1 is not empty - chose minimal from it (1), and remove it from the array.
result array = { 3, 4, 0, 5 }
proceed to STEP 4 "as planned"