Leetcode 628. Maximum Product of Three Numbers
Given an integer array nums
, find three numbers whose product is maximum and return the maximum product.
Input: nums = [1,2,3]
Output: 6
Input: nums = [1,2,3,4]
Output: 24
Input: nums = [-1,-2,-3]
Output: -6
By sorting the array, we can easily access the largest and smallest values to compute both scenarios and then return the maximum of the two products.
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
int maximumProduct(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int n = nums.size();
int product1 = nums[n-1] * nums[n-2] * nums[n-3];
int product2 = nums[0] * nums[1] * nums[n-1];
return std::max(product1, product2);
}
};
int main() {
Solution solution;
std::vector<int> nums1 = {1, 2, 3};
std::cout << "Maximum product of nums1: " << solution.maximumProduct(nums1) << std::endl;
std::vector<int> nums2 = {1, 2, 3, 4};
std::cout << "Maximum product of nums2: " << solution.maximumProduct(nums2) << std::endl;
std::vector<int> nums3 = {-1, -2, -3};
std::cout << "Maximum product of nums3: " << solution.maximumProduct(nums3) << std::endl;
return 0;
}
nums
takes O(n log n)
time, where n
is the number of elements in the array.O(1)
.Therefore, the overall time complexity is O(n log n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?