题目地址:https://leetcode.cn/problems/greatest-sum-divisible-by-three/description/
给你一个整数数组 nums,请你找出并返回能被三整除的元素 最大和。
// 思路:计算数组和sum 并算出sum%3的值mod
// 如果 sum % 3 == 1 , 那么移出一个余1 或者两个余2的元素即可
// 如果 sum % 3 == 2 , 那么移出一个余2 或者两个余1的元素即可
func maxSumDivThree(nums []int) int {
sum := 0
for _, n := range nums {
sum += n
}
mod := sum % 3
if mod == 0 {
return sum
}
rest1 := math.MaxInt
rest2Min1 := math.MaxInt
rest2Min2 := math.MaxInt
for _, n := range nums {
// 找到一个最小值
if n%3 == mod {
rest1 = min(rest1, n)
}
// 找到两个最小值
if (3 - n%3) == mod {
if n <= rest2Min1 {
rest2Min2 = rest2Min1
rest2Min1 = n
} else if n < rest2Min2 && n != rest2Min1 {
rest2Min2 = n
}
}
}
// 没有找到两个最小值
if rest2Min1 == math.MaxInt || rest2Min2 == math.MaxInt {
rest2Min1 = 0
rest2Min2 = math.MaxInt
}
return sum - min(rest1, rest2Min1+rest2Min2)
}
1008

被折叠的 条评论
为什么被折叠?



