Dynamic Programming -Candies

Alice is a kindergarten teacher. She wants to give some candies to the children in her class.  All the children sit in a line and each of them has a rating score according to his or her performance in the class.  Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy.

Example

She gives the students candy in the following minimal amounts: . She must buy a minimum of 10 candies.

1.至少1

2. higher rating more candies (由前往後比)

3.花最少candies

4.由後往前比 (當 前 > 後-> 2 1) 

       

 static long candies(int n, int[] arr) {
long count=0;
        int[] candies = new int[arr.length];
        for(int i=0;i<candies.length;i++){
            candies[i] = 1;
        }
        for(int i=0;i<arr.length-1;i++){
            if((arr[i+1] > arr[i]) && !(candies[i] < candies[i+1]))
                candies[i+1] = candies[i] + 1;
        }
        for(int i=arr.length-1;i>0;i--){
            if((arr[i] < arr[i-1]) && !(candies[i-1] > candies[i]))
            {
                candies[i-1] = candies[i] + 1;      
            }
        }
        for(int i=0;i<candies.length;i++)
            count += candies[i];
        return count;

    }

留言

這個網誌中的熱門文章

考績被打差了 輕率離職會更傷

Arrays - DS (Reverse array) [Easy]

WireMock