103-Candy

来源:互联网 发布:中级java程序员 编辑:程序博客网 时间:2024/04/29 04:13

–135. Candy My Submissions QuestionEditorial Solution
Total Accepted: 52699 Total Submissions: 232597 Difficulty: Hard
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?

题意: 给一队小孩一串数,现在发糖果,要求发糖果最少
满足 当前点邻域有序

面试碰到这个题:
1.特殊情况,递增或递减 直接就可以算出
2.非特殊呢?
当时思考时是先确定最小点的值,然后划分,后面发现子问题不满足同样特性,进一步思考,如何划分其实可以得到一种解,
就是 如果碰到两个值相等,中间就可以切开,问题是不一定有相同值
如果没相同值呢?那么有最小点集合,以最小点为切分对象。。转化为1,2

但不是最好的思路

最好的思路:
找到规律~
你想下只有顺序递增的时候,给糖果也是依次递增的
反过来呢,逆序递增的时候,给糖果也是逆序递增的
那么如何求出呢?
这样可以顺序扫描一遍,得出递增序列的糖果值
同样逆序扫描一遍,得出逆序递增的糖果值,当然递增的时候是取较大值的

整个过程不是很好理解,需要多举特例是想想过程

class Solution {public:    int candy(vector<int>& ratings) {       int n=ratings.size();       vector<int> increment(n,1);       int asc_len=1;       for(int i=1;i<n;++i){//顺序递增的时候           if(ratings[i]>ratings[i-1])                increment[i]=max(++asc_len,increment[i]);           else asc_len=1;       }       for(int j=n-1,asc_len=1;j>0;--j){//逆序递增的时候           if(ratings[j-1]>ratings[j])                increment[j-1]=max(++asc_len,increment[j-1]);           else asc_len=1;       }       return accumulate(increment.begin(),increment.end(),0);    }};//test case0://input:  2 3 2//output: 1 2 1//          1 2 1//          1 2 1//test case1:       //input:  1 2 3 4 3 2    //      1 2 3 4 1 1   //       1 1 1 3 2 1   //       1 2 3 4 2 1=13//testcase3: //input:1 2//output:1 2=3
0 0
原创粉丝点击