[LeetCode] Maximum Product of Two Elements in an Array

1464. Maximum Product of Two Elements in an Array

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).

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxProduct(vector<int>& nums) {
vector<int> S{nums[0], nums[1]};
for(int i = 2; i < nums.size(); i++) {
S.push_back(nums[i]);
sort(rbegin(S), rend(S));
S.pop_back();
}
return (S[0] - 1) * (S[1] - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/12/PS/LeetCode/maximum-product-of-two-elements-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.