leetcode---candy---dp
来源:互联网 发布:刘德华 知乎 编辑:程序博客网 时间:2024/05/22 10:29
There are N children standing in a line. Each child is assigned a rating value.
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.
What is the minimum candies you must give?
class Solution {public: int candy(vector<int> &ratings) { int n = ratings.size(); vector<int> dp(n, 0); dp[0] = 1; int sum = 1; if(n == 0) { return 0; } for(int i=1; i<n; i++) { if(ratings[i] > ratings[i-1]) { dp[i] = dp[i-1] + 1; sum += dp[i]; } else if(ratings[i] < ratings[i-1]) { if(i == 1) { dp[0] = 2; dp[1] = 1; sum = 3; } else { dp[i] = 1; int k = i-1; if(ratings[k] <= ratings[k-1]) { while(k > 0 && ratings[k] < ratings[k-1] && dp[k]+1 == dp[k-1]) { dp[k] += 1; k--; sum++; } dp[k] += 1; sum++; } sum += dp[i]; } } else { dp[i] = 1; sum += dp[i]; } } return sum; }};
阅读全文
0 0
- leetcode---candy---dp
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- 自然语言处理扫盲·第四天——白话人机问答系统原理
- 安卓线程消息handler和looper相关内容
- LWC 49:674. Longest Continuous Increasing Subsequence
- java 反射机制
- Android--(4)--EditText实现密码的点击显示与松开后不显示的效果
- leetcode---candy---dp
- 随机过程
- Spring 事务管理
- 网易笔试编程题——两种排序方法
- 网易秋招2018笔试题 重排数列
- JDBC连接池&DBUtils
- 虚拟化明星——深挖轻量级容器docker
- dpdk框架优化思路
- mysql 数据库整理——数据库添加删除