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

LeetCode 3487: Maximum Unique Subarray Sum After Deletion

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

基本資料
#

難易度: easy 第一次嘗試:2025-03-16

  • 提交紀錄:Wrong Answer ×2 → Accepted(2025-07-25)

解題思路
#

可以刪掉任意元素(但不能刪光),所以任何「值不重複」的一組元素都能留下來變成一個子陣列。問題就變成:挑一組不重複的值,總和最大。

  • 非負的值每種都拿一個(0 不影響總和)。
  • 如果全部都是負數,至少要留一個,就留最大的那個。

這是 Greedy 的「排序後掃描」型,只是這裡連排序都不用。

我的嘗試
#

版本問題
第一版只收集正數,全是負數時集合是空的,回傳 0。例如 [-3]:答案是 -3
第二版特判長度 1,但 [-5, -1] 還是回傳 0,答案是 -1
AC集合是空的時候,回傳所有負數中最大的

正確解法
#

class Solution:
    def maxSum(self, nums: List[int]) -> int:
        keep = set(x for x in nums if x >= 0)
        return sum(keep) if keep else max(nums)

複雜度
#

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

要特別避免的錯誤
#

  • 結果不能是空的:全是負數時要回傳最大值,不是 0。
  • 特判長度 1 不夠,要判斷的是「有沒有非負數」。

面試口說整理
#

因為可以任意刪除,任何一組不重複的值都能變成子陣列,所以我把每個非負的值各拿一次加總。如果沒有非負數,至少要留一個,就回傳最大的負數。時間 O(n)。

相關文章

LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種
LeetCode 3074: Apple Redistribution into Boxes
·1 分鐘
LeetCode Easy Array Greedy Sorting
LeetCode 3074 解題筆記:箱子可以隨便分,所以從容量最大的箱子開始拿,總容量夠裝所有蘋果就停
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2335: Minimum Amount of Time to Fill Cups
·1 分鐘
LeetCode Easy Array Greedy Sorting Heap-Priority-Queue
LeetCode 2335 解題筆記:答案是 max(最多的那種, ceil(總數 / 2));模擬的話每秒從最多的兩種各裝一杯
LeetCode 1122: Relative Sort Array
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 解題筆記:計數後先按照 arr2 的順序輸出,剩下的數由小到大接在後面
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對