2014年7月20日日曜日

Lesson 3: PassingCars (Passing Cars)

Note that each car traveling west will meet all the cars traveling east, which is coming form the opposite direction.

So in the following code, what it does is to count the number of cars traveling east from the head of the array, and when a car traveling west is found to then add the current value of the counter to cars traveling west to the counter of passing cars.

This strategy gives the score, 100%.









int solution(int A[], int N) 
{
    int cnt = 0;
    int cntCarsTravelingEast = 0;
    
    int i;
    for (i = 0; i < N; i++){
        if (A[i] == 0){
            cntCarsTravelingEast++;
        }
        else {
            cnt += cntCarsTravelingEast;             
            if (cnt > 1000000000){
                return -1;
            }
        }
    }
    
    return cnt;
}

0 件のコメント:

コメントを投稿