Maximum Product of Three Numbers
LeetCode 628 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
- `3 <= nums.length <= 10^4`
- `-1000 <= nums[i] <= 1000`
Topics: Array, Math, Sorting
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Sortingβ
Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?
When to use
Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.
Solutionsβ
Solution 1: C# (Best: 200 ms)β
| Metric | Value |
|---|---|
| Runtime | 200 ms |
| Memory | N/A |
| Date | 2018-04-13 |
Solution
public class Solution {
public int MaximumProduct(int[] nums) {
Array.Sort(nums);
int n = nums.Length;
return Math.Max(nums[n-1]*nums[n-2]*nums[n-3],nums[0]*nums[1]*nums[n-1]);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.