面试经典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;
    }
};
相关推荐
xiangyun6115 分钟前
【408数据结构 03】线性表与顺序表:C++手写SeqList
开发语言·数据结构·c++
Q26433650231 小时前
【有源码】基于机器学习的电信网络诈骗话术语义识别与可视化分析系统 XGBoost算法+Hadoop+Spark
大数据·hadoop·算法·机器学习·spark·毕业设计·课程设计
爱吃苹果的日记本1 小时前
数据结构第三课补充(空间复杂度)
数据结构·学习
不会就选b1 小时前
算法日常・每日刷题--贪心<11>
算法·leetcode·职场和发展
多弗朗皮卡丘1 小时前
数据结构6:队列
c语言·数据结构
千里码aicood1 小时前
面向电商冷启动与数据稀疏性的协同过滤算法优化研究
大数据·算法·协同过滤
xxxiugou1231 小时前
双指针解题秘籍:从入门到精通
c语言·数据结构·c++·算法
代码中介商1 小时前
C++ 预约系统实战(一):项目总览与 C/S 架构设计
c语言·开发语言·c++
能源革命1 小时前
TimesFM(Time Series Foundation Model)介绍
算法·能源
猎嘤一号1 小时前
学术训练(一)文献检索与阅读
人工智能·算法·机器学习·科研入门