面试经典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;
    }
};
相关推荐
得物技术8 分钟前
RAG—Chunking策略实战|得物技术
数据库·人工智能·算法
西哥写代码12 分钟前
基于dcmtk的dicom工具 第十章 读取dicom文件图像数据并显示
c++·mfc·dcmtk·vs2017
gugugu.1 小时前
算法:滑动窗口类型题目的总结
算法·哈希算法
澪吟2 小时前
数据结构入门:深入理解顺序表与链表
数据结构·链表
大数据张老师2 小时前
数据结构——直接插入排序
数据结构·算法·排序算法·1024程序员节
hoiii1872 小时前
基于SVM与HOG特征的交通标志检测与识别
算法·机器学习·支持向量机
进击的炸酱面2 小时前
第四章 决策树
算法·决策树·机器学习
爱coding的橙子2 小时前
每日算法刷题Day81:10.29:leetcode 回溯5道题,用时2h
算法·leetcode·职场和发展
lsnm2 小时前
C++新手项目-JsonRPC框架
开发语言·c++·1024程序员节
大千AI助手3 小时前
Householder变换:线性代数中的镜像反射器
人工智能·线性代数·算法·决策树·机器学习·qr分解·householder算法