• 문제 링크
Maximum Product of Three Numbers - LeetCode
Can you solve this real interview question? Maximum Product of Three Numbers - You are 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 Explanation: The o
leetcode.com
• 풀이 코드
public class Solution {
public int maximumProduct(int[] nums) {
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE, min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int n : nums) {
if (n > max1) {
max3 = max2;
max2 = max1;
max1 = n;
} else if (n > max2) {
max3 = max2;
max2 = n;
} else if (n > max3) max3 = n;
if (n < min1) {
min2 = min1;
min1 = n;
} else if (n < min2) min2 = n;
}
return Math.max(max1 * max2 * max3, min1 * min2 * max1);
}
/*public int maximumProduct(int[] nums) {
Arrays.sort(nums);
return Math.max(nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3], nums[0] * nums[1] * nums[nums.length - 1]);
}*/
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 643. Maximum Average Subarray I - Java (0) | 2026.09.15 |
|---|---|
| [LeetCode] 637. Average of Levels in Binary Tree - Java (0) | 2026.09.14 |
| [LeetCode] 617. Merge Two Binary Trees - Java (0) | 2026.09.12 |
| [LeetCode] 605. Can Place Flowers - Java (0) | 2026.09.11 |
| [LeetCode] 599. Minimum Index Sum of Two Lists - Java (0) | 2026.09.10 |
댓글