Advertisement

Maximum Product of Three Numbers - LeetCode 628 Solution

Maximum Product of Three Numbers - Complete Solution Guide

Maximum Product of Three Numbers is LeetCode problem 628, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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

Detailed Explanation

The problem asks us to find the maximum product of three numbers from a given integer array. The array contains at least three numbers and can have both positive and negative numbers. The goal is to return the largest possible product that can be achieved by multiplying any three elements in the array, respecting the constraints on the array's length and element values.

Solution Approach

The solution involves sorting the input array and then comparing two possible products: the product of the three largest numbers in the array and the product of the two smallest numbers and the largest number. The larger of these two products is the maximum product.

Step-by-Step Algorithm

  1. Step 1: Sort the input array 'nums' in ascending order.
  2. Step 2: Calculate the product of the three largest numbers in the array: nums[n-1] * nums[n-2] * nums[n-3], where 'n' is the length of the array.
  3. Step 3: Calculate the product of the two smallest numbers and the largest number: nums[0] * nums[1] * nums[n-1].
  4. Step 4: Return the maximum of the two calculated products.

Key Insights

  • Insight 1: The maximum product can be formed either by the three largest positive numbers or by the two smallest (most negative) numbers multiplied by the largest positive number. The presence of negative numbers changes the nature of the problem.
  • Insight 2: Sorting the array makes it easier to identify the smallest and largest numbers efficiently.
  • Insight 3: We need to consider the edge case where the two smallest numbers are very large negative numbers, and the largest number is positive; their product can be greater than the product of the three largest numbers.

Complexity Analysis

Time Complexity: O(n log n)

Space Complexity: O(1)

Topics

This problem involves: Array, Math, Sorting.

Companies

Asked at: FreshWorks, Infosys, Intuit, Nutanix, Roku, Salesforce, Siemens.