↓快轉到主要內容
  1. LeetCode/

LeetCode 3951: Minimum Energy to Maintain Brightness

·1 分鐘· ·
LeetCode Medium Array Sorting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-06-11

  • 提交紀錄:Accepted(一次通過)

解題思路
#

拆成兩件互不影響的事:

  1. 每個時間單位要開幾盞:一盞燈照亮自己和左右兩格,最多 3 個位置,所以至少要 ceil(brightness / 3) 盞。這個數量也一定做得到:把燈放在 1、4、7…,每盞照 3 格不重疊,最後一盞如果超出範圍就放在 n - 1,總共照到 min(3k, n) >= brightness 格(題目保證 brightness <= n)。
  2. 哪些時間單位要開:被至少一個區間覆蓋的時間。區間可能重疊,排序後合併再算總長度(Array 模板五)。

答案是兩者相乘。

我的解法
#

class Solution:
    def minEnergy(self, n: int, brightness: int, intervals: List[List[int]]) -> int:
        bulbs = (brightness + 2) // 3                  # ceil(brightness / 3)
        total = 0
        cur_s, cur_e = None, None
        for s, e in sorted(intervals):
            if cur_e is not None and s <= cur_e:       # 重疊(包含共用端點)就合併
                cur_e = max(cur_e, e)
            else:
                if cur_e is not None:
                    total += cur_e - cur_s + 1
                cur_s, cur_e = s, e
        total += cur_e - cur_s + 1
        return total * bulbs

複雜度
#

時間 O(m log m),m 是區間數,空間 O(m)(排序)。

要特別避免的錯誤
#

  • 區間是包含兩端的整數時間,長度是 e - s + 1,合併時共用端點也算重疊。
  • ceil(b / 3) 用整數寫成 (b + 2) // 3。

面試口說整理
#

每盞燈最多照亮 3 個位置,所以每個時間單位需要 ceil(brightness / 3) 盞,而且一定排得出來。需要開燈的時間是區間的聯集,我排序後合併算出總長度,再乘上每單位的燈數。時間 O(m log m)。

相關文章

LeetCode 522: Longest Uncommon Subsequence II
·1 分鐘
LeetCode Medium Two-Pointers String Sorting Array Hash-Table
LeetCode 522 解題筆記:最長的特殊子序列一定是某個完整字串;依長度由長到短檢查,只要不是其他夠長字串的子序列就是答案
LeetCode 3555: Smallest Subarray to Sort in Every Sliding Window
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array Monotonic-Stack
LeetCode 3555 解題筆記:每個長度 k 的視窗都是一次 LeetCode 581;n 只有 1000,對每個視窗跑 O(k) 的兩次掃描即可
LeetCode 581: Shortest Unsorted Continuous Subarray
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array Monotonic-Stack
LeetCode 581 解題筆記:從左往右記最大值,最後一個比最大值小的位置是右界;從右往左記最小值,最後一個比最小值大的位置是左界
LeetCode 3323: Minimize Connected Groups by Inserting Interval
·1 分鐘
LeetCode Medium Sliding-Window Sorting Binary-Search Array
LeetCode 3323 解題筆記:先合併區間;新區間能把第 l 到 r 組連起來 ⇔ 第 r 組的起點 − 第 l 組的終點 <= k;滑動視窗找一次能連起來最多組
LeetCode 1877: Minimize Maximum Pair Sum in Array
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 1877 解題筆記:排序後最小配最大、次小配次大,對撞指針取配對和的最大值
LeetCode 1040: Moving Stones Until Consecutive II
·1 分鐘
LeetCode Medium Sliding-Window Math Sorting Array
LeetCode 1040 解題筆記:最多步數 = 總空位 − 第一步會浪費掉的那一邊空隙;最少步數用長度 n 的視窗找最多石頭,n - 1 顆已連續、剩一顆在遠處時要特判成 2