프로그래머스/연습문제 Level2

프로그래머스 연습문제 LV2 - 최댓값과 최솟값

맴썰 2021. 9. 14. 21:18

문제 설명

문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution을 완성하세요.
예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다.

제한 조건

  • s에는 둘 이상의 정수가 공백으로 구분되어 있습니다.

입출력 예

s                                                                                              return

"1 2 3 4" "1 4"
"-1 -2 -3 -4" "-4 -1"
"-1 -1" "-1 -1"

 


import java.util.Arrays;
class Solution {
    public String solution(String s) {
        String answer = "";
        int max=0, min = 0;
        String[] temp = s.split(" ");
        int[] temp2 = new int[temp.length];
        int idx =0;
        for(int i=0; i<temp.length; i++){
            if(temp[i].equals("")) continue;
            temp2[idx++] = Integer.parseInt(temp[i]);
        }
        int t1 = temp2[0];int t2 = temp2[0];
        for(int i=1; i<temp2.length; i++){
            max = Math.max(t1,temp2[i]);
            min = Math.min(t2,temp2[i]);
            t1 = max; t2 = min;
        }
        answer = answer.concat(String.valueOf(min)).concat(" ").concat(String.valueOf(max));
        return answer;
        
    }
}