This problem looks busy at first, but the accepted solution is built around one steady invariant. For 561. Array Partition I, the solution in this repository is mainly a greedy solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are compare, arrayPairSum.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
03
04Example 1:
05Input: [1,4,3,2]
06
07Output: 4
08Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
09Note:
10n is a positive integer, which is in the range of [1, 10000].
11All the integers in the array will be in the range of [-10000, 10000].
12**/
13
14//Your runtime beats 8.12 % of cpp submissions. using sort()
15//Your runtime beats 31.66 % of cpp submissions. using qsort()
16
17class Solution {
18public:
19 static int compare (const void * a, const void * b)
20 {
21 return ( *(int*)a - *(int*)b );
22 }
23
24 int arrayPairSum(vector<int>& nums) {
25 int ans = 0;
26 // sort(nums.begin(), nums.end());
27
28 //https://stackoverflow.com/questions/12308243/trying-to-use-qsort-with-vector
29 qsort(&nums[0], nums.size(), sizeof(int), compare);
30
31 for(int i = 0; i < nums.size(); i++){
32 if(i%2==0) ans+=nums[i];
33 }
34 return ans;
35 }
36};
Cost