面试经典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;
    }
};
相关推荐
Accerlator4 分钟前
RAG 评测
算法
小鬼头编程5 分钟前
信息学竞赛体系(CSP-J/S、NOIP、NOI、IOI)
c++·人工智能·青少年编程
码哥DFS9 分钟前
算法练习day1-备战2027届秋招
前端·javascript·数据结构·算法
我不是懒洋洋23 分钟前
从零实现一个分布式数据管道:dbt的核心设计
c++
wabs66630 分钟前
关于图论【卡码网108.多余的边的思考】
数据结构·算法·图论
三克的油40 分钟前
数据结构-5
数据结构
Darkwanderor1 小时前
使用管道实现进程间通信 (IPC, Inter-Process Communitation)
linux·c语言·c++
乱七八糟的屋子1 小时前
【C++数值计算】Armadillo超详细入门教程
c++·线性代数·数值计算·科学计算·矩阵运算·armadillo
Yyyyyy~1 小时前
【C++】vector
c++·c++primer
冻柠檬飞冰走茶1 小时前
PTA基础编程题目集 7-37 整数分解为若干项之和(C语言实现)
c语言·开发语言·数据结构·算法