面试经典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;
    }
};
相关推荐
Lucas. Wáng2 小时前
Qt学习之旅
c++·qt
星恒随风3 小时前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
青少儿编程课堂3 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z3 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu4 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥4 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
csdn_aspnet4 小时前
C++ 求给定点集的简单闭合路径(Find Simple Closed Path for a given set of points)
c++
艾莉丝努力练剑5 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Severus_black5 小时前
【C++初阶】模板进阶
c语言·c++·学习
AAA修煤气灶刘哥5 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法