최댓값 만들기 (2)
정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 return하도록 solution 함수를 완성해주세요.
-10,000 ≤ numbers의 원소 ≤ 10,000
2 ≤ numbers 의 길이 ≤ 100
💻 풀이
i != j를 비교해 준다.📌 역시나.. 이중for문은 시간복잡도가 크다 ㅠㅠ
⌛ 시간 8.70ms ~ 10.78ms
public int solution(int[] numbers) {
// 기존에 최소값을 문제에서 나올 수 있는 가장 최소의 수로 설정
int max = -10000 * 10000;
for(int i = 0; i < numbers.length -1; i++) {
int n = 0;
for(int j = 1; j < numbers.length; j++) {
if(i != j) {
n = numbers[i] * numbers[j];
}
if(n > max) {
max = n;
}
}
}
return max;
}
💻 풀이
Arrays.sort() 로 오름차순 정렬을 해준다.Math.max(a, b) 를 사용해준다.⌛ 시간 0.33ms ~ 0.47ms
전체코드
public int solution1(int[] numbers) {
Arrays.sort(numbers);
int index = numbers.length - 1;
return Math.max(numbers[0] * numbers[1], numbers[index] * numbers[index -1]);
}