728x90
https://www.hackerrank.com/challenges/icecream-parlor/problem
Ice Cream Parlor | HackerRank
Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.
www.hackerrank.com
Algorithms > Search
아이스크림의 맛에 대한 가격 리스트가 주어지면,
두 개의 아이스크림을 골라 그 가격의 합이 가지고 있는 돈과 같게 되는 경우를 찾는 문제다.
코드
int* icecreamParlor(int m, int arr_count, int* arr, int* result_count) {
*result_count = 2;
int* cost = malloc(2*sizeof(int));
for(int i = 0; i < arr_count; i++){
for(int j = i + 1; j < arr_count; j++){
if((arr[i] + arr[j]) == m){
cost[0]=i+1;
cost[1]=j+1;
break;
}
}
}
return cost;
}
설명
동적 배열 cost를 만들고, 두 개의 가격 arr[i], arr[j]의 합이 m과 같은지 비교한다.
만약 두 가격의 합이 m과 같으면 cost 배열에 각각 해당 인덱스+1 값을 저장하고, for 루프를 빠져나온다.
이렇게 되면 cost에는 두 개의 아이스크림의 가격의 합이 주어진 돈과 같아질 때 그 값이 저장된 상태가 되므로 cost 배열을 리턴하면 문제를 해결할 수 있다.
728x90
'C & C++ > HackerRank' 카테고리의 다른 글
[HackerRank] Divisible Sum Pairs (0) | 2021.07.09 |
---|---|
[HackerRank] Find the Median (0) | 2021.06.25 |
[HackerRank] Tree: Height of a Binary Tree (0) | 2021.05.29 |
[HackerRank] Tree: Inorder Traversal (0) | 2021.05.19 |
[HackerRank] Tree: Postorder Traversal (0) | 2021.05.13 |