๐Ÿค–/์•Œ๊ณ ๋ฆฌ์ฆ˜ ์žฌํ™œ์šด๋™

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Java] ์ตœ์†Ÿ๊ฐ’ ๋งŒ๋“ค๊ธฐ

sssbin 2025. 3. 11. 17:48

 

https://school.programmers.co.kr/learn/courses/30/lessons/12941

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

 


ํ‹€๋ฆฐ ์ฝ”๋“œ

 

import java.util.*;
import java.util.stream.*;

class Solution
{
    public int solution(int []A, int []B)
    {
        List<Integer> listA = Arrays.stream(A)
                                .boxed()
                                .collect(Collectors.toList());

        List<Integer> listB = Arrays.stream(B)
                                .boxed()
                                .collect(Collectors.toList());
        
        Collections.sort(listA);
        Collections.sort(listB, Comparator.reverseOrder());
        
        int answer = 0;
        for (int i=0; i<listA.size(); i++) {
            answer += listA.get(i) * listB.get(i);
        }
        return answer;
    }
}

 

๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์„ ์œ„ํ•ด int[] -> List ๋ณ€ํ™˜

 

 

์ž๋ฐ”์˜ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์€ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๋‹ค๊ณ  ํ•จ.


์ •๋‹ต ์ฝ”๋“œ

import java.util.*;

class Solution
{
    public int solution(int []A, int []B)
    {
        Arrays.sort(A);
        Arrays.sort(B);
        
        int size = A.length;
        int answer = 0;
        
        for (int i=0; i<size; i++) {
            answer += A[i] * B[size-i-1];
        }
        
        return answer;
    }
}

 

๋‘˜๋‹ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ => List ๋ฐ stream ๋ถˆํ•„์š”