← Static tasks

628. Maximum Product of Three Numbers

leetcode easy

#array#csharp#easy#leetcode#math#sort

Task

Задав целочисленный массив nums, найдите три числа, произведение которых максимально, и верните максимальное произведение.

Пример:

Input: nums = [1,2,3]

Output: 6

C# solution

matched/original
public class Solution {
    public int MaximumProduct(int[] nums) {
        Array.Sort(nums);
        int n = nums.Length;
        int max1 = nums[n - 1] * nums[n - 2] * nums[n - 3];
        int max2 = nums[0] * nums[1] * nums[n - 1];
        return Math.Max(max1, max2);
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int MaximumProduct(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int max1 = nums[n - 1] * nums[n - 2] * nums[n - 3];
        int max2 = nums[0] * nums[1] * nums[n - 1];
        return max(max1, max2);
    }
}

Java solution

matched/original
import java.util.Arrays;

public class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int max1 = nums[n - 1] * nums[n - 2] * nums[n - 3];
        int max2 = nums[0] * nums[1] * nums[n - 1];
        return Math.max(max1, max2);
    }
}

JavaScript solution

matched/original
function maximumProduct(nums) {
    nums.sort((a, b) => a - b);
    const n = nums.length;
    const max1 = nums[n - 1] * nums[n - 2] * nums[n - 3];
    const max2 = nums[0] * nums[1] * nums[n - 1];
    return Math.max(max1, max2);
}

Python solution

matched/original
def maximumProduct(nums):
    nums.sort()
    max1 = nums[-1] * nums[-2] * nums[-3]
    max2 = nums[0] * nums[1] * nums[-1]
    return max(max1, max2)

Go solution

matched/original
package main

import (
    "sort"
)

func maximumProduct(nums []int) int {
    sort.Ints(nums)
    n := len(nums)
    max1 := nums[n-1] * nums[n-2] * nums[n-3]
    max2 := nums[0] * nums[1] * nums[n-1]
    if max1 > max2 {
        return max1
    }
    return max2
}

Explanation

Algorithm

Отсортируйте массив nums.

Найдите два возможных максимальных произведения: Произведение трех наибольших элементов массива. Произведение двух наименьших (отрицательных) и одного наибольшего элемента массива.

Верните максимальное из двух найденных произведений.

😎