← Back to LeetCode Notes

1464. Maximum Product of Two Elements in an Array

easy · array · sorting · heap-priority-queue · solved 2026.07.28 · 22 sec read

View on LeetCode ↗
C++
class Solution {public:    int maxProduct(vector<int>& nums) {        // keep track of best variable, value        std::priority_queue<int> best_i;        for (int i = 0; i < nums.size(); i++) {            best_i.push(nums[i]);        }        auto index1 = best_i.top();        best_i.pop();        auto index2 = best_i.top();        best_i.pop();        return (index1 - 1) * (index2 - 1);    }};

I did the double for loop method a first but that was inefficient time wise. but for some reason, i did not fully remember that the full question just is based around a single array. so when I wanted to do a priority queue implementation that means that i did not need to keep track of two priority queue for two indexes. I just needed the top two elements from the priority queue.