美文网首页
[LeetCode] 135. Candy (hard)

[LeetCode] 135. Candy (hard)

作者: 弱花 | 来源:发表于2018-11-02 11:33 被阅读0次

    原题

    思路:
    前后两遍遍历

    class Solution
    {
    public:
      int candy(vector<int> &ratings)
      {
        vector<int> res;
        int len = ratings.size();
        for (int i = 0; i < len; i++)
        {
          res.push_back(1);
        }
    
        for (int j = 0; j < len; j++)
        {
          if (j > 0 && ratings[j] > ratings[j - 1])
          {
            res[j] += res[j - 1];
          }
        }
    
    
        for (int k = len - 1; k >= 0; --k)
        {
          if (k < len - 1 && ratings[k] > ratings[k + 1] && res[k] <= res[k+1])
          {
            res[k] = res[k + 1]+1;
          }
        }
        int sum = 0;
        for (auto i : res)
        {
          cout<<i<<endl;
          sum += i;
        }
        return sum;
      }
    };
    

    相关文章

      网友评论

          本文标题:[LeetCode] 135. Candy (hard)

          本文链接:https://www.haomeiwen.com/subject/chiqxqtx.html