https://leetcode.com/problems/maximum-product-of-three-numbers/description/
Maximum Product of Three Numbers - LeetCode
Can you solve this real interview question? Maximum Product of Three Numbers - 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 = [
leetcode.com
정렬 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
내림차순으로 nums를 정렬해줍니다.
📔 풀이과정
배열을 내림차순으로 정렬하면 nums = [6, 5, 4, -1, -2]가 됩니다.
세 수의 곱이 최대가 되는 경우는 다음 두 가지입니다.
- 가장 큰 세 수를 선택하는 경우
6 × 5 × 4 = 120 - 가장 큰 수 하나와 가장 작은 두 수를 선택하는 경우
가장 작은 두 수가 모두 음수라면 두 수의 곱이 양수가 되므로,
6 × (-1) × (-2) = 12
양수 세 개를 선택할 때는 가장 큰 세 수를 선택해야 최대가 됩니다.
음수 두 개를 선택할 때는 절댓값이 가장 큰 음수 두 개, 즉 정렬된 배열의 가장 작은 두 수를 선택해야 그 곱이 최대가 됩니다. 중간 조합도 있을 수 있지만 같은 부호 조합에서는 극단값을 선택한 경우보다 커질 수 없으므로 비교할 필요가 없습니다.
따라서 두 경우만 비교하면 됩니다.
max(
nums[0] * nums[1] * nums[2],
nums[0] * nums[-1] * nums[-2]
)
위 예시에서는 max(120, 12)이므로 정답은 120입니다.
📔 정답 출력 | 반환
max(가장 큰 * 두 번째 큰 * 세 번째 큰 수끼리의 곱, 가장 큰 * 가장 작은 * 두 번째로 작은 수끼리의 곱)을 반환합니다.
📕 Code
📔 C++
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
int nSize = nums.size();
return max(nums[0] * nums[1] * nums[2], nums[0] * nums[nSize-1] * nums[nSize-2]);
}
};
📔 Python3
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort(reverse=True)
return max(
nums[0]*nums[1]*nums[2],
nums[0]*nums[-1]*nums[-2]
)
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Sorting' 카테고리의 다른 글
| (C++) - LeetCode (easy) 1051. Height Checker (0) | 2023.10.23 |
|---|---|
| (C++, Rust) - LeetCode (easy) 977. Squares of a Sorted Array (0) | 2023.09.15 |
| (C++) - LeetCode (easy) 561. Array Partition (0) | 2023.04.21 |
| (C++) - LeetCode (easy) 953. Verifying an Alien Dictionary (0) | 2023.02.02 |
| (C++) - LeetCode (easy) 88. Merge Sorted Array (0) | 2022.11.13 |