Given an integer array nums, you need to find three numbers whose product is the maximum possible and return this maximum product.
The array can contain both positive and negative integers, which makes this problem more interesting than it first appears! Consider that the product of two negative numbers is positive, so the maximum product might not always come from the three largest numbers.
Example: In array [1, 2, 3, 4], the maximum product is 2 × 3 × 4 = 24. But in array [-4, -3, -2, -1, 60], the maximum product is (-4) × (-3) × 60 = 720!
Your task is to efficiently find and return the maximum possible product of any three numbers from the array.
Input & Output
Visualization
Time & Space Complexity
Dominated by the sorting step, comparison is O(1)
Only using constant extra space for calculations (assuming in-place sort)
Constraints
- 3 ≤ nums.length ≤ 104
- -1000 ≤ nums[i] ≤ 1000
- The array will always have at least 3 elements