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

LeetCode 3909: Compare Sums of Bitonic Parts

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

基本資料
#

難易度: medium 第一次嘗試:2026-04-25

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

解題思路
#

陣列嚴格先升後降,所以山頂是唯一的。找到山頂之後,左邊是 nums[0..peak]、右邊是 nums[peak..n-1](Array 模板一)。山頂兩邊都算,比較大小時兩邊都加同一個數,所以可以都不加。

我的解法
#

class Solution:
    def compareBitonicSums(self, nums: List[int]) -> int:
        peak = nums.index(max(nums))
        left, right = sum(nums[:peak + 1]), sum(nums[peak:])
        if left > right:
            return 0
        if left < right:
            return 1
        return -1

我當時用兩個指標從兩端往山頂走,邊走邊加總(沒有加山頂)。嚴格雙調時最大值就是山頂,用 max 找也可以。

複雜度
#

時間 O(n),空間 O(n)(切片)。

要特別避免的錯誤
#

  • 回傳值的對應:左邊大回傳 0、右邊大回傳 1、相等回傳 -1。

面試口說整理
#

嚴格雙調的陣列最大值就是山頂,我找到山頂後分別加總兩邊再比較;山頂兩邊都有,所以不影響比較結果。時間 O(n)。

相關文章

LeetCode 3904: Smallest Stable Index II
·1 分鐘
LeetCode Medium Prefix-Sum Array
LeetCode 3904 解題筆記:前綴最大值減後綴最小值 <= k 的第一個 index;後綴最小值先從右往左建好
LeetCode 522: Longest Uncommon Subsequence II
·1 分鐘
LeetCode Medium Two-Pointers String Sorting Array Hash-Table
LeetCode 522 解題筆記:最長的特殊子序列一定是某個完整字串;依長度由長到短檢查,只要不是其他夠長字串的子序列就是答案
LeetCode 3843: First Element with Unique Frequency
·1 分鐘
LeetCode Medium Hash-Table Counting Array
LeetCode 3843 解題筆記:數每個值的次數,再數「每種次數有幾個值」;由左到右第一個次數只屬於它自己的就是答案
LeetCode 3840: House Robber V
·1 分鐘
LeetCode Medium Dynamic-Programming Array
LeetCode 3840 解題筆記:只有相鄰而且同色才衝突;顏色不同直接拿,同色時才做打家劫舍的取捨
LeetCode 3719: Longest Balanced Subarray I
·1 分鐘
LeetCode Medium Hash-Table Prefix-Sum Segment-Tree Array
LeetCode 3719 解題筆記:n 只有 1500,固定左端點往右擴,用兩個集合增量維護不同的奇數和偶數
LeetCode 3834: Merge Adjacent Equal Elements
·1 分鐘
LeetCode Medium Stack Simulation Array
LeetCode 3834 解題筆記:stack 模擬,新元素跟頂端相同就合併,合併後可能還要繼續跟新的頂端合併