2015年3月31日火曜日

Lesson 14: TieRopes (Tie Ropes)

Lesson 14: TieRopes 
https://codility.com/programmers/lessons/15

First, it had some time to think over the solution because I had some misunderstanding about the problem. Even when a rope became >= k, it can not be removed and remains in the same order even after being tied.(We can't remove the tied ropes even when they qualify the condition: length >= k.)

This suggests that we can use a greedy algorithm to tie ropes from the beginning.

Assume that we have the maximum number of ropes that is longer or equal to K and some ropes that is shorter than K are left untied now. Even when these ropes are tied to the ropes that is >= k on the right hand side won't increase the maximum number we already have; if not this contradicts the first assumption that we have the maximum number of the ropes (the length k >=0) already.

This strategy gives the 100% score as below.








int solution(int K, int A[], int N) 
{
    int cnt = 0;
    
    int current = 0;

    int i;
    for (i = 0; i < N; i++){
        current += A[i];
        if (current >= K){
            cnt++;
            current = 0;
        }
    }
    
    return cnt;
}

0 件のコメント:

コメントを投稿