프로그래머스 C# 최댓값 만들기2(List.Add, List.Max(), Linq, P, J)
using System;
using System.Collections.Generic;
public class Solution {
public int solution(int[] numbers) {
int max = 0;
int max1 = -999999999;
for(int i=0;i<numbers.Length;i++)
{
for(int j=0;j<numbers.Length;j++)
{
if(i == j)
{
continue;
}
else
{
max = (numbers[i])*(numbers[j]);
if(max > max1)
{
max1 = max;
}
}
}
}
return max1;
}
}
// 1번 방법 Linq없이 그냥 하는 법
// 7번째 테스트에서 에러가 나는데 아마 [9999, -10000] 뭐 이런 케이스인 거 같다. max1을 -999999999로 하니까 에러가 안나기는 함.
//
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int solution(int[] numbers) {
List<int> list = new List<int>();
for(int i = 0; i < numbers.Length; i++)
{
for(int j = 0; j < numbers.Length; j++)
{
if(i == j)
{
continue;
}
else
{
list.Add(numbers[i] * numbers[j]);
}
}
}
return list.Max();
}
}
// 링크를 사용하는 방법. 코드는 이게 더 쉽다.
using System;
public class Solution {
public int solution(int[] numbers) {
int maxLen = numbers.Length-1;
Array.Sort(numbers);
return (int)MathF.Max(numbers[0]*numbers[1], numbers[maxLen]*numbers[maxLen-1]);
}
}
///
자바
import java.util.*;
class Solution {
public int solution(int[] numbers) {
int len = numbers.length;
Arrays.sort(numbers);
return Math.max(numbers[0] * numbers[1], numbers[len - 2] * numbers[len - 1]);
}
}
파이썬
def solution(numbers):
numbers = sorted(numbers)
return max(numbers[0] * numbers[1], numbers[-1]*numbers[-2])