面试经典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;
    }
};
相关推荐
牛油果子哥q19 小时前
C++六大默认成员函数深度精讲:构造/析构/拷贝/赋值/移动构造/移动赋值、编译器生成规则、深浅拷贝终极坑点与工程实战
开发语言·c++
Shadow(⊙o⊙)19 小时前
System V共享内存详解,shm系列接口,三种共享内存删除机制。System V通信缺点分析
linux·运维·服务器·开发语言·网络·c++
lightqjx19 小时前
【算法】数据结构_并查集
数据结构·算法·并查集
小雨下雨的雨19 小时前
鸿蒙PC Electron框架实现流体气泡模拟器
前端·人工智能·算法·华为·electron·鸿蒙
txzrxz19 小时前
广度优先搜索详解(BFS)
算法·宽度优先
小小de风呀19 小时前
de风——【从零开始学C++】(十三):优先级队列 priority_queue 全解析 & 仿函数入门
开发语言·c++
8Qi819 小时前
LeetCode 198:打家劫舍(House Robber)—— 题解 ✅
算法·leetcode·动态规划
王老师青少年编程19 小时前
信奥赛C++提高组csp-s之搜索进阶(记忆化搜索案例实践1)
c++·记忆化搜索·搜索·信奥赛·csp-s·提高组·滑雪
无限码力19 小时前
华为非AI方向0603笔试真题-爆破小游戏(详细思路+多语言题解)
算法·华为·华为笔试真题·华为非ai笔试真题
wunaiqiezixin19 小时前
扫描线算法
算法