面试经典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 <= ratingsi <= 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;
    }
};
相关推荐
tkevinjd1 分钟前
力扣72-编辑距离
算法·leetcode·职场和发展
小刘学技术10 分钟前
AI人工智能决策树分类器:原理、实现与应用
开发语言·人工智能·python·算法·决策树·机器学习·数据挖掘
脱胎换骨-军哥11 分钟前
C++ 嵌入式编程实例:从寄存器操作到底层驱动开发
开发语言·c++·驱动开发
鱼子星_32 分钟前
【C++】vector
开发语言·c++·笔记·stl
吃着火锅x唱着歌36 分钟前
Effective C++ 学习笔记 条款38 通过复合塑模出has-a或“根据某物实现出”
c++·笔记·学习
syagain_zsx40 分钟前
库制作与原理 · 链接知识笔记
c语言·c++·笔记·动态库·静态库
qz5zwangzihan140 分钟前
题解:Atcoder Beginner Contest abc467 A~D
c++·题解·atcoder·abc467
caimouse1 小时前
mm学习笔记_04:VAD树算法与地址空间分配
笔记·学习·算法·reactos
abcy0712131 小时前
flink窗口类型
开发语言·python·算法
jinyishu_11 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式