面试经典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;
    }
};
相关推荐
charlie11451419115 分钟前
现代C++工程实践:简单的IniParser3——改进我们的split
开发语言·c++·笔记·学习
fish_xk17 分钟前
c++的引用和类的初见
开发语言·c++
灰灰勇闯IT42 分钟前
【探索实战】Kurator多集群统一应用分发实战:从环境搭建到业务落地全流程
算法
鱼在树上飞1 小时前
乘积最大子数组
算法
H_z___1 小时前
Codeforces Round 1070 (Div. 2) A~D F
数据结构·算法
晨尘光1 小时前
【Windows 下FlatBuffers 编译.fbs文件并应用】
c++·windows
自学小白菜1 小时前
每周刷题 - 第三周 - 双指针专题 - 02
python·算法·leetcode
杜子不疼.2 小时前
【LeetCode76_滑动窗口】最小覆盖子串问题
算法·哈希算法
煤球王子2 小时前
学而时习之:C++中的文件处理2
c++
ComputerInBook2 小时前
代数基本概念理解——特征向量和特征值
人工智能·算法·机器学习·线性变换·特征值·特征向量