[Programmers] #120862 - 최댓값 만들기 (2) [Java][C++][Python]
[Programmers] #120862 - 최댓값 만들기 (2) [Java][C++][Python]
1. 아이디어
정수 배열 numbers의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 구하는 문제로 원소가 0 또는 음수가 될 수 있어서 2중 반복문을 통해 모든 경우를 탐색하는 방식으로 해결했다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N^2)$ | $O(1)$ |
($N$ = numbers의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int solution(int[] numbers) {
int max = -Integer.MAX_VALUE;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = i + 1; j < numbers.length; j++) {
max = Math.max(max, numbers[i] * numbers[j]);
}
}
return max;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;
int solution(vector<int> numbers) {
int mx = -INT_MAX;
for (int i = 0; i < numbers.size() - 1; i++) {
for (int j = i + 1; j < numbers.size(); j++) {
mx = max(mx, numbers[i] * numbers[j]);
}
}
return mx;
}
1
2
3
4
5
from itertools import combinations
def solution(numbers):
return max(a * b for a, b in combinations(numbers, 2))
combinations(numbers, 2)로 서로 다른 두 원소의 쌍을 전부 훑고, 각 쌍의 곱을 제너레이터로 max에 넘겨 이중 루프와 최댓값 변수 없이 한 줄로 처리했다.
This post is licensed under CC BY 4.0 by the author.