1262. Greatest Sum Divisible by Three
https://leetcode.com/problems/greatest-sum-divisible-by-three/description/
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).Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.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)./*
* @lc app=leetcode id=1262 lang=cpp
*
* [1262] Greatest Sum Divisible by Three
*/
// @lc code=start
class Solution {
public:
int maxSumDivThree(vector<int>& nums) {
vector<int> dp = {0, INT_MIN, INT_MIN};
for (const auto num : nums) {
auto n_dp = vector<int>(3, 0);
for (int i = 0; i < 3; ++i) {
n_dp[(num + i) % 3] = max(dp[(num + i) % 3], dp[i] + num);
}
swap(dp, n_dp);
}
return dp[0];
}
};
// @lc code=end
Last updated