Leetcode - Valid Perfect Square
Leetcode - Sqrt(x)

Leetcode - Greatest Sum Divisible by Three

violet posted @ May 10, 2020 01:29:15 AM in 算法 with tags Algorithm Golang 非人也 , 246 阅读

https://leetcode.com/problems/greatest-sum-divisible-by-three/

Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.

 

Example 1:

Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).

Example 2:

Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.

Example 3:

Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).

 

func maxSumDivThree(nums []int) int {
    leftOne := 20000
    leftTwo := 20000
    result := 0
    for _, n := range nums {
        result += n
        if n % 3 == 1 {
            leftTwo = min(leftTwo, leftOne+n)
            leftOne = min(leftOne, n)
        }
        if n % 3 == 2 {
            leftOne = min(leftOne, leftTwo+n)
            leftTwo = min(leftTwo, n)
        }
    }
    if result % 3 == 0 {
        return result
    }
    if result % 3 == 1 {
        return result - leftOne
    }
    return result - leftTwo
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter