InterviewStreet --Candies

题目来源:https://www.interviewstreet.com/challenges/dashboard/#problem/4fe12e4cbb829

解题报告:

递增情况下,就一直value++, sum += value

如果前后两值相等,就设value=1, sum += value

如果递减,则记录上一次递增或相等时的最后一点的value值preValue,及位置preCur,然后设当前一点value为1,然后从preCur到当前点的之间的vaule值都要相应的+1,所以sum += i - preCur -1。然后还要判断preValue值是否比它下个数的加完1后的结果大,如果小的话,preValue值也要+1,相应的sum也要+1。

这样一次遍历就可以获得结果,算法复杂度O(n)


#include 
using namespace std;

int main()
    {
        int N;
        cin >> N;
        int *a = new int[N];
        for (int i = 0; i < N; i++)
        {
            cin >> a[i];
        }
        int preCur = 0;
        int sum = 0;
        int value = 1;
        int preValue = 1;
        sum += value;
        for (int i = 1; i < N; i++)
        {
            if (a[i] < a[i-1])
            {
                if (preCur == i-1)
                {
                    preValue = value;
                    value = 1;
                }
                else
                {
                    sum += (i - preCur -1);
                    value = 1;
                }
                if (i - preCur + 1 > preValue)
                {
                    preValue++;
                    sum++;
                }
            }
            else
            {
                if (a[i] > a[i-1])
                    value++;
                else if (a[i] == a[i-1])
                    value = 1;
                preCur = i;
            }
            sum += value;
        }
        cout << sum << endl;
    }



附录:

Alice is a kindergarden 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 usual performance.  Alice wants to give at least 1 candy for each child.Children get jealous of their immediate neighbors, so if two children sit next to each other then the one with the higher rating must get more candies. Alice wants to save money, so she wants to minimize the total number of candies.
 
 
Input
 
The first line of the input is an integer N, the number of children in Alice's class. Each of the following N lines contains an integer indicates the rating of each child.
 
Ouput
 
Output a single line containing the minimum number of candies Alice must give.
 
Sample Input
 
3
1
2
2
 
Sample Ouput
 
4
 
Explanation
 
The number of candies Alice must give are 1, 2 and 1.
 
Constraints:
 
N and the rating  of each child are no larger than 10^5.
 

你可能感兴趣的:(InterviewStreet --Candies)