code第一部分数组:第二十一题:分糖果

code第一部分数组:第二十一题:分糖果

 

给糖果,每人至少一颗,高分孩子得到比左右多,求糖果数。
there are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
• Each child must have at least one candy.
• Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?

 

#include <iostream>

using namespace std;

int max(int a,int b)
{
    if (a>=b)
    {
        return a;
    }
    else
        return b;
}

int candy(int* ratings,int n)
{
    int result=0;

    const int m=n;
    int increment[m];

    for (int i = 1; i < n; i++)
    {
        if (ratings[i] > ratings[i-1])
        {
            increment[i] = increment[i-1]+1;
            cout<<"increment[i]"<<increment[i]<<endl;
        }
        else
        {
            increment[i] = 1;
            cout<<"increment[i]"<<increment[i]<<endl;
        }
    }

    for (int i = n - 2; i >= 0; i--)
    {
        if (ratings[i] > ratings[i + 1])
        {
            increment[i] =max(increment[i+1]+1,increment[i]);
            cout<<"increment[i]"<<increment[i]<<endl;
        }
        else
        {
            increment[i]= 1;
            cout<<"increment[i]"<<increment[i]<<endl;
        }
    }

    for (int i = 0; i < n; i++)
    {
        result += increment[i];
    }

    return result;
}

int main()
{
    int a[5]={1,3,2,4,5};

    int ans = candy(a,5);

    cout<<"at least candy number is "<<ans<<endl;

    return 0;
}

 

posted @ 2017-02-25 22:17  taoliu_alex  阅读(282)  评论(0编辑  收藏  举报