Coding Test/LeetCode

[LeetCode] 1464. Maximum Product of Two Elements in an Array c++

owls 2023. 2. 21. 15:47
728x90

문제

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

 

문제 해결

class Solution {
public:
     int maxProduct(vector<int>& nums) {
        int first = 0, second = 0;
        
        for( const int& number: nums){
            
            if( number > first ){
                second = first;
                first = number;
                
            }else if( number > second ){
                second = number;
            }
        }
     return ( first - 1 ) * ( second - 1 );
	}
};

 

 

 

다른  풀이

class Solution {
public:
     int maxProduct(vector<int>& nums) {
        priority_queue<int> pq(begin(nums), end(nums));
        
        int result = (pq.top() - 1);
        pq.pop();
        result *= (pq.top() - 1);
        pq.pop();
        
        return result;  
    }
};

 

728x90