Maximum Product of Two Elements in an Array Solutions in C++
Number 1464
Difficulty Easy
Acceptance 77.9%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/// Author : Hao Chen// Date : 2020-10-02class Solution {public:int maxProduct(vector<int>& nums) {int max1=max(nums[0], nums[1]);int max2=min(nums[0], nums[1]);for (int i=2; i< nums.size(); i++) {if (nums[i] > max1) {max2 = max1;max1 = nums[i];continue;}else if (nums[i] > max2) {max2 = nums[i];}}return (max1-1)*(max2-1);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array//// Author : liuyubobobo/// Time : 2020-05-30#include <iostream>#include <vector>using namespace std;/// Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(1)class Solution {public:int maxProduct(vector<int>& nums) {int res = 0;for(int i = 0; i < nums.size(); i ++)for(int j = i + 1; j < nums.size(); j ++)res = max(res, (nums[i] - 1) * (nums[j] - 1));return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array//// Author : liuyubobobo/// Time : 2020-06-05#include <iostream>#include <vector>using namespace std;/// Sorting/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:int maxProduct(vector<int>& nums) {sort(nums.begin(), nums.end(), greater<int>());return (nums[0] - 1) * (nums[1] - 1);}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array//// Author : liuyubobobo/// Time : 2020-06-05#include <iostream>#include <vector>using namespace std;/// Linear Scan to find the largest and the second largest/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:int maxProduct(vector<int>& nums) {int a = -1, b = -1;for(int e: nums)if(e >= a) b = a, a = e;else if(e > b) b = e;return (a - 1) * (b - 1);}};int main() {return 0;}