【每日一题Day115】LC2335装满杯子需要的最短总时长 | 贪心

简介: 【每日一题Day115】LC2335装满杯子需要的最短总时长 | 贪心

装满杯子需要的最短总时长【LC2335】

You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.


You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.

什么时候天晴呀(又在草稿里没发出来)

  • 思路:如果存在两个杯子,那么每次装两杯;如果只存在一个杯子,那么每次装一杯。因此每次选择最大值和次大值进行装杯,尽可能每次装满两个杯子,减小最短时长。那么总时长取决于杯子的最大值m a x 与剩下两个值的和s u m − 的大小关系:
  • 杯子的最大值大于剩下两个值的和,在装该类水杯时,可以顺便把另外两个装满,那么总时长即为杯子的最大值个数。杯子的最大值小于等于剩下两个值的和,那么每次选择最大值和次大值进行装杯,那么总时长即为⌈ s u m / 2 ⌉ 。
  • 局部最优:三种杯子的数量均匀减小,每次尽可能装满两个杯子
  • 全局最优:装满杯子的总时长最短
  • 实现
class Solution {
    public int fillCups(int[] amount) {
        int max = 0;
        int sum = 0;
        for (int num : amount){
            sum += num;
            max = Math.max(num, max);
        }
        if (max > sum - max) {
            return max;
        }else{
            return sum / 2 + sum % 2;
        }
    }
}

复杂度

时间复杂度:O ( 1 )

空间复杂度:O ( 1 )


目录
相关文章
|
5天前
【每日一题Day141】LC2379得到 K 个黑块的最少涂色次数 | 滑动窗口
【每日一题Day141】LC2379得到 K 个黑块的最少涂色次数 | 滑动窗口
20 0
|
5天前
【每日一题Day342】LC2578最小和分割 | 贪心
【每日一题Day342】LC2578最小和分割 | 贪心
21 0
|
5天前
【每日一题Day118】LC1124表现良好的最长时间段 | 前缀和+单调栈/哈希表
【每日一题Day118】LC1124表现良好的最长时间段 | 前缀和+单调栈/哈希表
32 0
|
5天前
|
存储
【每日一题Day123】LC1792最大平均通过率 | 堆
【每日一题Day123】LC1792最大平均通过率 | 堆
30 0
|
5天前
leetcode-6112:装满杯子需要的最短总时长
leetcode-6112:装满杯子需要的最短总时长
28 0
|
5天前
【每日一题Day319】LC2594修车的最少时间 | 二分答案
【每日一题Day319】LC2594修车的最少时间 | 二分答案
16 0
|
5天前
|
存储 算法
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
22 0
|
5天前
【每日一题Day208】LC1335工作计划的最低难度 | 动态规划
【每日一题Day208】LC1335工作计划的最低难度 | 动态规划
28 0
|
5天前
【每日一题Day160】LC1092最短公共超序列 | 动态规划
【每日一题Day160】LC1092最短公共超序列 | 动态规划
22 0
【每日一题Day160】LC1092最短公共超序列 | 动态规划
|
5天前
【每日一题Day314】LC1921消灭怪物的最大数量 | 贪心+排序
【每日一题Day314】LC1921消灭怪物的最大数量 | 贪心+排序
23 0