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

LeetCode135☞分糖果

关联LeetCode题号135

本题特点
  • 贪心
  • 两次遍历,一次正序遍历,只比较左边,左边比右边大的情况 i-1 i
  • 一次倒序遍历,只比较右边的,右边比左边大 i+1 i
本题思路
class Solution:
    def candy(self, ratings: List[int]) -> int:
        candy = [1] * len(ratings)
        # 右大于左
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i-1]:
                candy[i] = candy[i-1] + 1
        # 左大于右
        for j in range(len(ratings)-2, -1, -1):
            if ratings[j] > ratings[j+1]:
                candy[j] = max(candy[j+1]+1, candy[j])
        print(candy)
        return sum(candy)
package leetcode;

import org.junit.jupiter.api.Test;

/**
 * File Description: Candy
 * Author: Your Name
 * Date: 2024/12/24
 */
public class Candy_135 {
    public int candy(int[] ratings) {
        int[] candy = new int[ratings.length];
        candy[0] = 1;
        for (int i=1; i<ratings.length; i++){
//            if (ratings[i-1] < ratings[i]){
//                candy[i] = candy[i-1] + 1;
//            }else{
//                candy[i] = 1;
//            }
            candy[i] = (ratings[i-1] < ratings[i]) ? candy[i-1]+1 : 1;
        }
        for(int j=ratings.length-2; j>=0; j--){
            if (ratings[j] > ratings[j+1]){
                candy[j] = Math.max(candy[j], candy[j+1]+1);
            }

        }
        int sum = 0;
        for(int c: candy){
            sum += c;
        }
        return sum;
    }

    @Test
    public void TestCandy(){
        int[] rating = {1,0,2};
        System.out.println(candy(rating));
    }
}

http://www.kler.cn/a/593236.html

相关文章:

  • FreeSWITCH:开源通信平台的全栈解决方案
  • 荣耀手机卸载应用商店、快应用中心等系统自带的
  • Vue.js 插槽(Slot)详解:让组件更灵活、更强大
  • 开源链动 2+1 模式 AI 智能名片 S2B2C 商城小程序助力社群发展中榜样影响力的提升
  • 基于springboot+vue的调查问卷平台
  • Oracle OCP认证没落了吗?
  • 【leetcode100】搜索插入位置
  • ADQ12DC-PCIe总线直流耦合1G采集卡
  • 【leetcode100】搜索二维矩阵
  • Android Room 框架测试模块源码深度剖析(五)
  • Linux驱动开发-①pinctrl 和 gpio 子系统②并发和竞争③内核定时器
  • 【模拟】从 0 到 1:模拟算法的深度剖析与实战指南
  • 实验4 Vue.js路由实验
  • 【AI论文】ReCamMaster:基于单视频的相机控制式生成渲染
  • 如何打造企业 DevOps 文化
  • LeetCode 第22~24题
  • Java学习------初识JVM体系结构
  • 【C++】 —— 笔试刷题day_6
  • 如何实现一个DNS
  • Lora 中 怎么 实现 矩阵压缩