【数组】分糖果问题

求解代码

java 复制代码
public int candy(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }

        int n = arr.length;
        int[] candyCount = new int[n]; // 定义数组记录每个孩子最终应分得的糖果数
        int ans = 0; // 统计分发糖果的总数量

        // 每个孩子至少分得1颗糖果
        for(int i=0;i<arr.length;i++){
            candyCount[i]=1;
        }

        // 从左到右遍历数组,保证相邻孩子中,右侧评分更高的孩子糖果数多于左侧
        for(int i=1;i<n;i++){
            if(arr[i] > arr[i-1]){
                candyCount[i] = candyCount[i-1] + 1;
            }
        }

        // 从右到左遍历数组,保证相邻孩子中,左侧评分更高的孩子糖果数多于右侧
        for(int i=n-2;i>=0;i--){
            if(arr[i] > arr[i+1] && candyCount[i] <= candyCount[i+1]){
                candyCount[i] = candyCount[i+1] + 1;
            }
        }

        // 累加所有孩子的糖果数,得到分发的总数量
        for (int i = 0; i < n; i++) {
            ans += candyCount[i];
        }
        // 返回总糖果数
        return ans;
    }
相关推荐
2301_764441331 天前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI1 天前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
014-code1 天前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024061 天前
组合模式(Composite Pattern)
开发语言
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法
游乐码1 天前
c#泛型约束
开发语言·c#
Dontla1 天前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen1 天前
python rest请求、requests
开发语言·python
feifeigo1231 天前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法