3487. Maximum Unique Subarray Sum After Deletion - Easy
前往題目
思路
這題寫出來了
- 用Set紀錄重複的,且跳過小於1的數字
- 切記要追蹤並判斷是否全部都是負數,全部都是負數的話反而要輸出最大負數,只要有一個正數(>=0),就一定不會是輸出負數
Code
class Solution {
public int maxSum(int[] nums) {
HashSet<Integer> set = new HashSet();
int res = 0;
boolean isAllNegative = true;
for (int num : nums) {
// Record non negative
if (num >= 0) isAllNegative = false;
// Duplicate || num smaller than 1
if (set.contains(num) || num < 1) continue;
// Add to the set
set.add(num);
// Add up
res += num;
}
if (isAllNegative) {
res = Integer.MIN_VALUE;
for (int num : nums) {
res = Math.max(res, num);
}
}
return res;
}
}
3487. Maximum Unique Subarray Sum After Deletion - Easy
https://f88083.github.io/2025/03/16/3487-Maximum-Unique-Subarray-Sum-After-Deletion-Easy/