-
[LeetCode] 1464. Maximum Product of Two Elements in an Array c++Coding Test/LeetCode 2023. 2. 21. 15:47728x90
문제
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'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 653. Two Sum IV - Input is a BST c++ (0) 2023.02.22 [LeetCode] 206. Reverse Linked List c++ (0) 2023.01.04 [LeetCode] 21. Merge Two Sorted Lists c++ (0) 2023.01.04 [LeetCode] 994. Rotting Oranges c++ (0) 2023.01.04 [LeetCode] 542. 01 Matrix c++ (0) 2023.01.03