面试经典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;
    }
};
相关推荐
Yingye Zhu(HPXXZYY)35 分钟前
ICPC 2023 Nanjing R L 题 Elevator
算法
晚风(●•σ )2 小时前
C++语言程序设计——06 字符串
开发语言·c++
苏小瀚3 小时前
[数据结构] ArrayList(顺序表)与LinkedList(链表)
数据结构
晚云与城3 小时前
今日分享:C++ -- list 容器
开发语言·c++
阿维的博客日记3 小时前
LeetCode 139. 单词拆分 - 动态规划解法详解
leetcode·动态规划·代理模式
兰雪簪轩3 小时前
分布式通信平台测试报告
开发语言·网络·c++·网络协议·测试报告
程序员Xu4 小时前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
笑脸惹桃花4 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法
深度学习·算法·yolo·torch·cuda
阿维的博客日记5 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
GEO_YScsn5 小时前
Rust 的生命周期与借用检查:安全性深度保障的基石
网络·算法