Approach
Sorting and greedy selection
For Maximize Pair Strength Using Gcd, 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
- 39 lines of C++ from the credited upstream file maximize-pair-strength-using-gcd.cpp.
- The implementation visibly relies on sequence storage.
- 4 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 long long maxPairStrength(vector<int>& nums) {8 sort(begin(nums), end(nums), greater<int>());9 int64_t result = 0;10 for (int i = 0; i < size(nums); ++i) {11 for (int j = i + 1; j < size(nums); ++j) {12 if (static_cast<int64_t>(nums[i]) * nums[j] <= result) {13 break;14 }15 const int64_t g = gcd(nums[i], nums[j]);16 result = max(result, (nums[i] / g) * (nums[j] / g));17 }18 }19 return result;20 }21};22 23242526class Solution2 {27public:28 long long maxPairStrength(vector<int>& nums) {29 int64_t result = 0;30 for (int i = 0; i < size(nums); ++i) {31 for (int j = i + 1; j < size(nums); ++j) {32 const int64_t g = gcd(nums[i], nums[j]);33 result = max(result, (nums[i] / g) * (nums[j] / g));34 }35 }36 return result;37 }38};39