628. Maximum Product of Three Numbers
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.
Задав 정수 배열 nums, find три числа, произведение которых максимально, и return максимальное произведение.
예제:
Input: nums = [1,2,3]
Output: 6
C# 해법
매칭됨/원본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++ 해법
자동 초안, 제출 전 검토#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 해법
매칭됨/원본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 해법
매칭됨/원본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 해법
매칭됨/원본def maximumProduct(nums):
nums.sort()
max1 = nums[-1] * nums[-2] * nums[-3]
max2 = nums[0] * nums[1] * nums[-1]
return max(max1, max2)
Go 해법
매칭됨/원본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
}
Algorithm
Отсортируйте 배열 nums.
find два возможных максимальных произведения: Произведение трех наибольших elementов 배열а. Произведение двух наименьших (отрицательных) и одного наибольшего elementа 배열а.
return максимальное из двух найденных произведений.
😎
Vacancies for this task
활성 채용 with overlapping task tags are 표시됨.
아직 활성 채용이 없습니다.