본문 바로가기

c언어 스터디/HackerRank

[HackerRank] Search- Sherlock and Array

Sherlock and Array | HackerRank

 

Sherlock and Array | HackerRank

Check whether there exists an element in the array such that sum of elements on its left is equal to the sum of elements on its right.

www.hackerrank.com

 

<문제>

배열을 입력받아, 왼쪽 원소들의 합과 오른쪽 원소들의 합이 같으면 yes, 그런 짝이 없으면 no를 반환한다.

 

input: 첫번째 줄에는 입력받을 테스트 케이스의 개수를 입력받는다.

두번째 줄부터는 배열을 입력받는데, 첫째 줄에는 배열의 크기, 그리고 두번째 줄에는 배열의 원소를 차례로 입력받는다.

output: 왼쪽 원소와 오른쪽 원소 중 합이 같은 경우가 하나라도 있으면 yes, 없으면 no를 출력한다.

 

 

<코드>

char* balancedSums(int arr_count, int* arr) {
    int total=0;
    int mid,pre_sum=0;
    // 전체 합 구하기
    for(int i=0;i<arr_count;i++){
        total=total+arr[i];
    }
    
    // yes, no 리턴하기
    for(int i=0;i<arr_count;i++){
        pre_sum=pre_sum+arr[i-1];
        if(total-(arr[i]+pre_sum)==pre_sum)
            return "YES";
    }
    return "NO";
}

<풀이>

배열의 전체합을 구하고, for문을 돌리면서 앞에서부터 하나씩 다시 더하면서 전체합에서 더한 값과 현재 위치한 원소값을 뺐을 때, 뺀 값과 더한값이 같으면 yes를 출력하게 하면 문제를 풀 수 있을거라고 생각했다.

첫번째 for문을 통해 배열의 전체합을 total 변수에 저장하였다.
다음 for문에서 다시 앞에서부터 하나씩 더하면서 pre_sum변수에 저장하였고, total - arr[i] - pre_sum 값이 pre_sum과 같으면 yes를 출력하도록 하여 문제를 풀 수 있었다.

 

 

<실행결과>