Address https://www.acwing.com/solution/leetcode/content/6340/
Title Description
give you an array of integers nums, and returns you to identify the elements that can be divisible by three and maximum.
Example 1 : Input: the nums = [ 3 , 6 , . 5 , 1 , 8 ] output: 18 Explanation: select number 3 , 6 , 1 and 8 , and they are 18 (which may be 3 divisible and maximum). Example 2 : Input: the nums = [ 4 ] Output: 0 Explanation: 4 can not be 3 divisible numbers can not be selected, returns 0 . Example 3 : Input: the nums = [ . 1 , 2, 3 , 4 , 4 ] Output: 12 Explanation: selected number 1 , 3 , 4 and 4 , and they are 12 (which may be 3 divisible and maximum). Tip: . 1 <= nums.length <= . 4 * 10 ^ . 4 . 1 <= the nums [I] <= 10 ^ . 4
Algorithm 1
last arrays, and only three cases
1 divided by 3 0 direct return of more than
2 divided by more than 31 then either a reduction of more than 31 digital divide or reduce the number more than two divided by 32 is
3 is divided by 3 2 then divided by either a reduction of more than 32 digital or reduce the number more than two divided by 3 1
class Solution { public: vector<int> v[3]; int Check(int singleIdx,int doubleIdx,int sum) { if (v[doubleIdx].size() < 2) { return sum - v[singleIdx][0]; } else if (v[singleIdx].size() == 0) { return sum - v[doubleIdx][0] - v[doubleIdx][1]; } else { int rem = v[singleIdx][0]; if (rem > (v[doubleIdx][0] + v[doubleIdx][1])) rem = (v[doubleIdx][0] + v[doubleIdx][1]); return sum - rem; } } int maxSumDivThree(vector<int>& nums) { int sum = 0; for (int i = 0; i < nums.size(); i++) { sum += nums[i]; if (nums[i] % 3 == 1) { v[1].push_back(nums[i]); } else if(nums[i] % 3 == 2){ v[2].push_back(nums[i]); } } sort(v[1].begin(), v[1].end()); sort(v[2].begin(), v[2].end()); int sum_n = sum % 3; if (sum_n == 0) return sum; if (sum_n == 1) { // reduce a two v1 and v2 select return the Check ( . 1 , 2 , SUM); } IF (sum_n == 2 ) { return the Check ( 2 , . 1 , SUM); } return - . 1 ; } };