面试经典150题——Day15

文章目录

一、题目

135. Candy

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

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.

Return the minimum number of candies you need to have to distribute the candies to the children.

Example 1:

Input: ratings = [1,0,2]

Output: 5

Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: ratings = [1,2,2]

Output: 4

Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.

The third child gets 1 candy because it satisfies the above two conditions.

Constraints:

n == ratings.length

1 <= n <= 2 * 104

0 <= ratings[i] <= 2 * 104

题目来源:leetcode

二、题解

每次处理一边的情况

cpp 复制代码
class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size();
        vector<int> candies(n,1);
        //右边比左边大的情况
        for(int i = 1;i < n;i++){
            if(ratings[i] > ratings[i-1]) candies[i] = candies[i-1] + 1;
        }
        //左边比右边大的情况
        for(int i = n - 2;i >= 0;i--){
            if(ratings[i] > ratings[i+1]) candies[i] = max(candies[i],candies[i+1] + 1);
        }
        int res = 0;
        for(int i = 0;i < n;i++){
            res += candies[i];
        }
        return res;
    }
};
相关推荐
然我24 分钟前
链表指针玩不转?从基础到双指针,JS 实战带你破局
前端·数据结构·算法
EndingCoder32 分钟前
算法与前端的可访问性
前端·算法·递归·树形结构
洛克希德马丁1 小时前
QTableView鼠标双击先触发单击信号
c++·qt
ysa0510301 小时前
竞赛常用加速技巧#模板
c++·笔记·算法
7 971 小时前
C语言基础知识--文件的顺序读写与随机读写
java·数据结构·算法
2401_841003981 小时前
Kubernetes 资源管理全解析
算法·贪心算法
exm-zem2 小时前
多用户图书管理系统
c++
☆璇2 小时前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
我要成为c嘎嘎大王2 小时前
【C++】初识C++(1)
开发语言·c++
艾莉丝努力练剑5 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表