LeetCode Blog

Solutions for LeetCode problems - Written by ansidev

628. Maximum Product of Three Numbers

Author's avatar
ansidev Posted on November 18, 2022

Problem

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:

Analysis

If length of nums is 3, maximum product is nums[0] x nums[1] x nums[2].

Approaches

Approach 1

Notes:
- l: length of nums.
- nums[i:j]: sub array of nums from index i to j (includes nums[i], nums[j]).

Approach

Solutions

import "sort"

func maximumProduct(nums []int) int {
	l := len(nums)

	if l == 3 {
		return nums[0] * nums[1] * nums[2]
	}

	sort.Ints(nums)

	return max(nums[0]*nums[1]*nums[l-1], nums[l-3]*nums[l-2]*nums[l-1])
}

func max(x int, y int) int {
	if x > y {
		return x
	}

	return y
}

Complexity