The trick here is to name the state correctly, then let the implementation follow. For 1464. Maximum Product of Two Elements in an Array, the solution in this repository is mainly a greedy solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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.
The notes already sitting in the source point us in the right direction:
- sort
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxProduct.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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//sort
02//Runtime: 16 ms, faster than 58.26% of C++ online submissions for Maximum Product of Two Elements in an Array.
03//Memory Usage: 9.9 MB, less than 100.00% of C++ online submissions for Maximum Product of Two Elements in an Array.
04class Solution {
05public:
06 int maxProduct(vector<int>& nums) {
07 sort(nums.rbegin(), nums.rend());
08
09 return (nums[0]-1) * (nums[1]-1);
10 }
11};
12
13//nth_element
14//Runtime: 8 ms, faster than 96.88% of C++ online submissions for Maximum Product of Two Elements in an Array.
15//Memory Usage: 10.1 MB, less than 100.00% of C++ online submissions for Maximum Product of Two Elements in an Array.
16class Solution {
17public:
18 int maxProduct(vector<int>& nums) {
19 nth_element(nums.begin(), nums.begin()+2, nums.end(),
20 greater<int>());
21
22 return (nums[0]-1) * (nums[1]-1);
23 }
24};
Cost