Beats 100% of users with C++|| Using Max and Second Max Approach || Faster Solution
Intuition\r\n Describe your first thoughts on how to solve this problem. \r\n\r\nif you like the approach please upvote it\r\n\r\n\r\n\r\n\r\n\r\n\r\nif you lik
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\nif you like the approach please upvote it\r\n\r\n\r\n\r\n![image.png](https://assets.leetcode.com/users/images/7495fea3-7639-48a4-8ad9-79dc9237db4e_1701793058.7524364.png)\r\n\r\n\r\nif you like the approach please upvote it\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\nfirst get max element and then second maximum element \r\nthen minimum element and second minimum element \r\n\r\n1- product of max and second max\r\n2- product of min and second min\r\n3- difference of max product and min product \r\n4- return the difference\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O ( N )\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O ( 1 )\r\n\r\n# Code\r\n```\r\nclass Solution {\r\npublic:\r\n    int maxProductDifference(vector<int>& nums) \r\n    {\r\n        int size=nums.size();\r\n        int max;\r\n        int sec_max;\r\n        int min;\r\n        int sec_min;\r\n        if(nums[0]>nums[1])\r\n        {\r\n            max=nums[0];\r\n            sec_max=nums[1];\r\n            min=sec_max;\r\n            sec_min=max;\r\n        }\r\n        else\r\n        {\r\n            sec_max=nums[0];\r\n            max=nums[1];\r\n            min=sec_max;\r\n            sec_min=max;\r\n        }\r\n        for(int i=2;i<size;i++)\r\n        {\r\n            if(nums[i]>max)\r\n            {\r\n                sec_max=max;\r\n                max=nums[i];\r\n            }\r\n            else if(nums[i]>sec_max)\r\n                sec_max=nums[i];\r\n            if(nums[i]<min)\r\n            {\r\n                sec_min=min;\r\n                min=nums[i];\r\n            }\r\n            else if(nums[i]<sec_min)\r\n                sec_min=nums[i];\r\n        }\r\n        return (sec_max*max)-(min*sec_min);\r\n    }\r\n};\r\n```
['Array', 'Math', 'Sorting', 'C++']