N个孩子站成一排,给每个人设定一个权重(已知)。按照如下的规则分配糖果: (1)每个孩子至少分得一颗糖果
(2)权重较高的孩子,会比他的邻居获得更多的糖果。
问:总共最少需要多少颗糖果?请分析算法思路,以及算法的时间,空间复杂度是多少。
/* N个孩子站成一排,给每个人设定一个权重(已知)。按照如下的规则分配糖果: (1)每个孩子至少分得一颗糖果 (2)权重较高的孩子,会比他的邻居获得更多的糖果。 问:总共最少需要多少颗糖果?请分析算法思路,以及算法的时间,空间复杂度是多少。 */ #include <stdio.h> void handout(int* child, int nCount, int* Candy, int* pTotalCandy); int main() { int nTotalCandy = 0; int childWeight[] = {1, 8, 3, 2, 2, 6, 4, 8}; int candy[sizeof(childWeight) / sizeof(childWeight[0])] = {0}; handout(childWeight, sizeof(childWeight) / sizeof(childWeight[0]), candy, &nTotalCandy); printf("Total:%d\n", nTotalCandy); for (int i = 0; i < sizeof(childWeight) / sizeof(childWeight[0]); i++) { printf("%d ", candy[i]); } printf("\n"); return 0; } void handout(int* childWeight, int nCount, int* Candy, int* pTotalCandy) { int nLastCandy = 0; int nLastWeight = -1; int nTotalCandy = 0; for (int i = 0; i < nCount; i++) { //大于 糖果 + 1 if (childWeight[i] > nLastWeight) { Candy[i] = ++nLastCandy; nLastWeight = childWeight[i]; nTotalCandy += Candy[i]; } //等于 糖果不变 else if (childWeight[i] == nLastWeight) { Candy[i] = nLastCandy; nLastWeight = childWeight[i]; nTotalCandy += Candy[i]; } //小于 糖果 -1 else if (childWeight[i] < nLastWeight) { Candy[i] = --nLastCandy; nLastWeight = childWeight[i]; nTotalCandy += Candy[i]; //如果前一个糖果是1,则之前的每人再发一个 if (nLastCandy == 0) { for (int j = 0; j <= i; j++) { ++Candy[j]; } nLastCandy++; nTotalCandy += i + 1; } } } *pTotalCandy = nTotalCandy; }
int candy(vector<int> &ratings) { int i,j,sum = 0,min = ratings[0],n = ratings.size(); int dp[n+1]={0}; if (n<2)return 1; for (i = 0;i<n;i++) dp[i] = 1; for (i = 0;i<n;i++) { if (i<n-1&&ratings[i+1]>ratings[i]) dp[i+1]=dp[i]+1; } for (i = n-1;i>=0;i--) { if (i>0&&ratings[i-1]>ratings[i]&&dp[i-1]<dp[i]+1) dp[i-1]=dp[i]+1; sum += dp[i]; } return sum; }