Maximum Product Of Two Elements In Array||Beats 100%💯|| Full commented code with explanation✅✅
Approach\n Describe your approach to solving the problem. \n- largest and secondLargest are initialized to the minimum integer value. \n- The code iterates thro
# Approach\n<!-- Describe your approach to solving the problem. -->\n- `largest` and `secondLargest` are initialized to the minimum integer value. \n- The code iterates through the input array nums. For each element `nums[i]`, it compares with the current largest and secondLargest.\n- If `nums[i]` is greater than the current largest, it becomes the new largest, and the previous largest becomes the new secondLargest.\n- If `nums[i]` is not greater than largest but is greater than the current secondLargest, it becomes the new secondLargest.\n- After iterating through the array and finding the two largest elements, the code calculates the maximum product of two largest elements. `(largest-1) * (secondLargest-1)`\n- ALSO NOTE WE HAVE NOT CHECKED FOR `nums[i]<largest` IN ELSE IF LOOP BECAUSE WE ARE NOT GIVEN THAT THE TWO NUMBERS SHOULD BE UNIQUE.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int maxProduct(int[] nums) {\n        // Initialize\n        int largest = Integer.MIN_VALUE;\n        int secondLargest = Integer.MIN_VALUE;\n\n        // Iterate through the array to find the two largest elements.\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i] > largest) {\n                // If the current element is greater than the largest, update both largest and secondLargest.\n                secondLargest = largest;\n                largest = nums[i];\n            } else if (nums[i] > secondLargest) {\n                // If the current element is greater than the second largest, update only secondLargest.\n                secondLargest = nums[i];\n            }\n        }\n\n        // Calculate the maximum product of two largest elements minus 1.\n        int ans = (largest - 1) * (secondLargest - 1);\n        return ans;\n    }\n}\n\n```
['Array', 'Sorting', 'Java']