728x90
https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
Breaking the Records | HackerRank
Given an array of Maria's basketball scores all season, determine the number of times she breaks her best and worst records.
www.hackerrank.com
Algorithms > Implementation
점수 배열이 주어지면 최저점과 최고점이 갱신되는 횟수를 각각 저장하여 배열로 리턴한다.
코드
int* breakingRecords(int scores_count, int* scores, int* result_count) {
*result_count = 2;
int *res = malloc(*result_count * sizeof(int));
int min = scores[0], max = scores[0];
int min_count = 0, max_count = 0;
for (int i = 1; i < scores_count; i++){
if (scores[i] < min) {
min = scores[i];
min_count++;
}
if (scores[i] > max) {
max = scores[i];
max_count++;
}
}
res[0] = max_count;
res[1] = min_count;
return res;
}
설명
리턴할 동적 배열 res를 선언한다.
최저점을 저장할 변수 min, 최고점을 저장할 변수 max를 선언해 둘 다 점수 배열의 첫 원소로 초기화하고,
최저점 경신 횟수를 저장할 변수 min_count, 최고점 경신 횟수를 저장할 변수 max_count를 선언한다.
for문을 돌면서 최저점과 최고점을 각 원소와 비교해 경신하고, 경신될 때마다 각각의 count를 1 증가시킨다.
모든 갱신 과정이 끝나면 res배열의 첫 원소를 max_count로, 두 번째 원소를 min_count로 지정하고 리턴한다.
728x90
'C & C++ > HackerRank' 카테고리의 다른 글
[HackerRank] Bill Division (1) | 2021.09.25 |
---|---|
[HackerRank] Counting Sort 1 (0) | 2021.09.25 |
[HackerRank] Running Time of Algorithms (0) | 2021.09.19 |
[HackerRank] Migratory Birds (0) | 2021.09.09 |
[HackerRank] The Power Sum (0) | 2021.09.09 |