[leetcode] 135. Candy (hard)

版权声明:by ruohua3kou https://blog.csdn.net/ruohua3kou/article/details/83069838

原题
前后两遍遍历

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;
  }
};

猜你喜欢

转载自blog.csdn.net/ruohua3kou/article/details/83069838
今日推荐