当前位置: 首页 > news >正文

面试经典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

二、题解

每次处理一边的情况

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;}
};
http://www.lryc.cn/news/199257.html

相关文章:

  • web APIs——第一天(上)
  • 【Leetcode】215. 数组中的第K个最大元素
  • 服务器数据恢复-RAID5常见故障的数据恢复方案
  • 12个VIM编辑器的高级玩法
  • ⽜客论坛的笔记
  • JS逆向分析某枝网的HMAC加密、wasm模块加密
  • 论坛介绍|COSCon'23开源商业(V)
  • 在word、ppt、excel编辑软件标题栏顶部左上角加入自定义功能:另存为、导出PDF
  • Flink学习笔记(三):Flink四种执行图
  • 堆-----数据结构
  • 震撼登场 | 拓世科技集团新品亮相成为2023世界VR产业大会全场焦点
  • 后端接口的查询方式
  • Maven首次安装配置
  • 使用html2canvas将html转pdf,由于table表的水平和竖直有滚动条导致显示不全(或者有空白)
  • EDID详解
  • 浅谈云原生
  • 【K8S】Kubernetes
  • 面试题 01.01. 判定字符是否唯一
  • C++(Qt)软件调试---linux使用dmesg定位程序崩溃位置(14)
  • 38 WEB漏洞-反序列化之PHPJAVA全解(下)
  • LeetCode 面试题 10.10. 数字流的秩
  • Vue3项目上线打包优化
  • 【算法题】2525. 根据规则将箱子分类
  • python字典
  • thinkphp队列的使用?
  • 【数据结构】排序--归并排序
  • 批量修改视频尺寸:简单易用的视频剪辑软件教程
  • 四川云汇优想:短视频矩阵运营方案
  • vue中如何获取到当前位置的天气
  • C++三角函数和反三角函数