LeetCode Solutions
628. Maximum Product of Three Numbers
Time: $O(n\log n)$ Space: $O(1)$
class Solution {
public:
int maximumProduct(vector<int>& nums) {
const int n = nums.size();
sort(begin(nums), end(nums));
return max(nums[n - 1] * nums[0] * nums[1],
nums[n - 1] * nums[n - 2] * nums[n - 3]);
}
};
class Solution {
public int maximumProduct(int[] nums) {
final int n = nums.length;
Arrays.sort(nums);
return Math.max(nums[n - 1] * nums[0] * nums[1], nums[n - 1] * nums[n - 2] * nums[n - 3]);
}
}
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
return max(nums[-1] * nums[0] * nums[1],
nums[-1] * nums[-2] * nums[-3])