首页 > 其他分享 >LeetCode 135. Candy

LeetCode 135. Candy

时间:2022-11-08 19:11:21浏览次数:38  
标签:ratings int Candy num 135 LeetCode size

贪心算法

贪心策略:在每次遍历中,仅考虑并更新相邻一侧的大小关系

class Solution {
public:
    int candy(vector<int>& ratings) {
        int size = ratings.size();
        if(size<2){
            return size;
        }
        vector<int> num(size,1);
        //从左到右
        for(int i=0;i<size-1;i++){
            if(ratings[i+1]>ratings[i])
                num[i+1] = num[i] + 1;
        }
        //从右到左
        for(int i=size-1;i>0;i--){
            if(ratings[i]<ratings[i-1])
                num[i-1] = max(num[i] + 1,num[i-1]);
        }
        return accumulate(num.begin(),num.end(),0);
    }
};

标签:ratings,int,Candy,num,135,LeetCode,size
From: https://www.cnblogs.com/poteitoutou/p/16870837.html

相关文章

  • LeetCode 455. Assign Cookies
    贪心classSolution{public:intfindContentChildren(vector<int>&g,vector<int>&s){sort(g.begin(),g.end());sort(s.begin(),s.end());......
  • Leetcode练题系列(六): 字符串相关的算法
    LeetCode  ​​英文官网(推荐)​​  ​​中文官网​​  从2016年大二左右开始就接触算法,起初也简单练习过,但现在工作一段时间后,随着代码水平的提高(​​自我感觉​​)......
  • 【Leetcode】 剑指offer:链表(简单)--Day02
    剑指Offer06.从尾到头打印链表可借助栈。或先遍历列表得到元素数,开辟数组空间倒序填入。剑指Offer24.反转链表可借助栈:classSolution{publicListNodere......
  • Leetcode第1684题:统计一致字符串的数目(Count the number of consistent strings)
    解题思路采用位运算的思路不太好理解。但思想就是根据allowed建立一个\(mask\),遍历words中的每个元素的每个字符c,查看\(mask\)的值是否为真。如果存在就返回结果加一。......
  • leetcode 541. 反转字符串 II
    题目给定一个字符串s和一个整数k,从字符串开头算起,每计数至2k个字符,就反转这2k字符中的前k个字符。如果剩余字符少于k个,则将剩余字符全部反转。如果剩余字符......
  • [LeetCode] 1544. Make The String Great
    Givenastring s ofloweranduppercaseEnglishletters.Agoodstringisastringwhichdoesn'thave twoadjacentcharacters s[i] and s[i+1] where:......
  • leetcode 35. 搜索插入位置 js 实现
    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(logn) 的算法。......
  • [LeetCode] 1323. Maximum 69 Number
    Youaregivenapositiveinteger num consistingonlyofdigits 6 and 9.Return themaximumnumberyoucangetbychanging atmost onedigit(6 becomes......
  • leetcode 300. 最长递增子序列 js 动态规划实现
    给你一个整数数组nums,找到其中最长严格递增子序列的长度。子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7]是数组[0......
  • LeetCode刷题记录.Day8
    两个数组的交集链接349.两个数组的交集-力扣(LeetCode)classSolution{public:vector<int>intersection(vector<int>&nums1,vector<int>&nums2){......