📜  门| GATE-CS-2015(Set 1)|问题3(1)

📅  最后修改于: 2023-12-03 15:12:42.499000             🧑  作者: Mango

GATE-CS-2015(Set 1) - Question 3

Introduction

GATE-CS-2015(Set 1)-Question 3 is a coding problem that requires you to implement a function that takes in a list of numbers and returns the maximum product of any three numbers in the list.

Problem Statement

Given a list of integers, find the maximum product of any three numbers.

Example
Input: [1, 2, 3, 4, 5, -6]
Output: 120
Solution

To solve this problem, we need to consider three cases:

  1. The three largest positive numbers
  2. The two smallest negative numbers and the largest positive number
  3. The three smallest negative numbers

The answer to the problem will be the maximum of these three cases.

def maximum_product_of_three_numbers(nums):
    nums.sort()
    n = len(nums)
    case1 = nums[n - 1] * nums[n - 2] * nums[n - 3]
    case2 = nums[0] * nums[1] * nums[n - 1]
    case3 = nums[0] * nums[1] * nums[2]
    return max(case1, case2, case3)
Explanation
  • We first sort the list of numbers in ascending order.
  • Case 1: This considers the scenario where the three largest positive numbers are present in the list. Hence, we multiply the last three numbers in the sorted list to get the maximum product.
  • Case 2: This considers the scenario where the two smallest negative numbers and the largest positive number are present in the list. Hence, we multiply the first two numbers in the sorted list with the last number to get the maximum product.
  • Case 3: This considers the scenario where the three smallest negative numbers are present in the list. Hence, we multiply the first three numbers in the sorted list to get the maximum product.
  • Finally, we return the maximum value of the three cases.
Time Complexity

The time complexity of this solution is O(n log n) because of the sorting algorithm used.

Space Complexity

The space complexity of this solution is O(1) because we are not using any extra space to store values.