Approach
Sorting and greedy selection
For Maximum Sum of Three Numbers Divisible by Three, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 59 lines of C++ from the credited upstream file maximum-sum-of-three-numbers-divisible-by-three.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int maximumSum(vector<int>& nums) {8 const auto& add = [](auto& arr, int x) {9 for (int i = 0; i < size(arr); ++i) {10 if (x > arr[i]) {11 swap(arr[i], x);12 }13 }14 if (size(arr) != 3) {15 arr.emplace_back(x);16 }17 };18 19 vector<vector<int>> group(3);20 for (const auto& x : nums) {21 add(group[x % 3], x);22 }23 int result = 0;24 for (auto& g : group) {25 if (size(g) == 3) {26 result = max(result, accumulate(cbegin(g), cend(g), 0));27 }28 }29 if (!empty(group[0]) && !empty(group[1]) && !empty(group[2])) {30 result = max(result, group[0][0] + group[1][0] + group[2][0]);31 }32 return result;33 }34};35 36373839class Solution2 {40public:41 int maximumSum(vector<int>& nums) {42 vector<vector<int>> group(3);43 for (const auto& x : nums) {44 group[x % 3].emplace_back(x);45 }46 int result = 0;47 for (auto& g : group) {48 sort(begin(g), end(g), greater<int>());49 if (size(g) >= 3) {50 result = max(result, accumulate(cbegin(g), cbegin(g) + 3, 0));51 }52 }53 if (!empty(group[0]) && !empty(group[1]) && !empty(group[2])) {54 result = max(result, group[0][0] + group[1][0] + group[2][0]);55 }56 return result;57 }58};59