Post

[Programmers] 120899번 - 가장 큰 수 찾기 [Java][C++]

[Programmers] 120899번 - 가장 큰 수 찾기 [Java][C++]

문제 링크


1. 아이디어

정수 배열 array에서 가장 큰 수와 그 수의 인덱스를 찾는 문제로 배열을 순회하며 최댓값이 등장할 때마다 그 값과 인덱스를 기억했다가 반환하는 방식으로 해결했다.


2. 복잡도

시간복잡도공간복잡도
$O(N)$$O(1)$

N = array 길이


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public int[] solution(int[] array) {
        int max = -1;
        int idx = -1;

        for (int i = 0; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
                idx = i;
            }
        }

        return new int[]{max, idx};
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> array) {
    int mx = -1;
    int idx = -1;

    for (int i = 0; i < array.size(); i++) {
        if (array[i] > mx) {
            mx = array[i];
            idx = i;
        }
    }

    return {mx, idx};
}

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