Post

Array_앞에있는 숫자들보다 커?_max

✅ 내 앞에 있는 숫자들보다 내가 제일 크면 출력

작거나 같아도 보이지 않습니다.
2중 for문을 만들 필요 없이 그냥 최대값이랑 비교하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Main {
    public int solution(int n, int[] arr){
        int answer=1;
        int max=arr[0];
        for(int i=1; i<n; i++){
            if(arr[i]> max){
                answer ++;
                max=arr[i];
            }
        }
        return answer;
}
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr= new int[n];
        for(int i= 0; i<n; i++){
            arr[i] = sc.nextInt();
        }
        System.out.println(T.solution(n, arr));
    }
}


//⭐️input:
//8
//130 135 148 140 145 150 150 153
//⭐️output:
//5

🔵 ThingsILearned

✔️ 2중 for문을 돌지 않아도 된다.

2중 for문 돌지 않고 바로 max에 새롭게 찾은 최댓값 추가해버리기
그리고 최대값과 새로운 값들 비교하기

🟢 2중 for문

하지만 이렇게 풀면 O의 n제곱이라 1초 넘어버린다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Main {
    public int solution(int n, int[] arr){
        int answer=0;
        for(int i=0; i<n; i++){
            int max=0;
            for(int j=0; j<i; j++){
                if(max < arr[j]){
                    max =  arr[j];
                }
            }
            if(arr[i] > max) answer +=1;

        }
        return answer;
}
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr= new int[n];
        for(int i= 0; i<n; i++){
            arr[i] = sc.nextInt();
        }
        System.out.println(T.solution(n, arr));
    }
}


This post is licensed under CC BY 4.0 by the author.