js solution


  • 0
    /**
     * @param {number[]} ratings
     * @return {number}
     */
    var candy = function(ratings) {
      var dp = [];
      for (var i = 0; i < ratings.length; i++)
        dp.push(1);
    
      for (var i = 1; i < ratings.length; i++)
        if (ratings[i] > ratings[i - 1])
          dp[i] = dp[i - 1] + 1;
    
      for (var i = ratings.length - 2; i >= 0; i--)
        if (ratings[i] > ratings[i + 1] && dp[i] <= dp[i + 1])
          dp[i] = dp[i + 1] + 1;
    
      var ans = 0;
      dp.forEach(function(item) {
        ans += item;
      });
      return ans;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.