LeetCode135. Candy (贪心)

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

几种情况观察
输入[2, 4, 6 ,8 ], 输出序列为[1, 2, 3, 4]
输入[8, 6, 4, 2], 输出序列为[4, 3, 2, 1]
输入[2, 4, 6, 8, 6, 4], 输出序列为[1, 2, 3, 4, 2, 1]
输入[2, 4, 6, 8, 6, 4, 2, 0], 输出序列为[1, 2, 3, 5, 4, 3, 2, 1]
输入[2,4, 6, 8, 8, 8, 6, 4,], 输出序列为[1, 2, 3, 4, 1, 3, 2, 1]

特殊情况的考虑
如只有一个元素,返回1;
所有元素都一致,返回全1;

模拟上过程

class Solution {
public:
    int candy(vector<int>& arr) {
        int n = arr.size();
        if(n==0) return 0;
        if(n==1) return 1;
        vector<int> sum(n+1, 0);
        for(int i=0;i+1<n;) {
            if(arr[i+1]==arr[i]) { 
                if(i==0) sum[0]=1; // 重点:否则过不了开始就连续相同元素的样例
                i++;
                sum[i]=1;
                continue;
		    }
            int j,k;
            for(j=i;j+1<n&&arr[j+1]>arr[j];j++);
            for(k=i;k+1<n&&arr[k+1]<arr[k];k++);
            if(j!=i) {
                sum[i]=1;
                for(int t=i+1;t<=j;t++) sum[t]=sum[t-1]+1;
                i=j;
            }
            else if(i!=k) {
                int len = k-i+1;
                if(sum[i]<len) sum[i]=len;
                sum[i+1]=len-1;
                for(int t=i+2;t<=k;t++) 
                    sum[t]=sum[t-1]-1;
                i=k;
            }

        }
        int ans=0;
        for(int i=0;i<n;i++)
            ans+=sum[i];
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值