23.07.04 Today’s Leetcode
137. Single Number II (medium)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
counter = Counter(nums)
for key in counter.keys():
if counter[key] == 1:
return key
return -1
2461. Maximum Sum of Distinct Subarrays With Length K (medium)
TLE : 66/92
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
counter = Counter(nums[:k])
num = sum(nums[:k])
def check(p):
count = 0
for key in p.keys():
if p[key] == 1:
count += 1
if p[key] > 1:
return False
return count == k
res = num if check(counter) else 0
for i in range(n - k):
counter[nums[i]] -= 1
num -= nums[i]
counter[nums[i + k]] += 1
num += nums[i + k]
res = max(res, num if check(counter) else 0)
return res
다른 카운팅 방식을 이용.
from collections import Counter
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
s = 0
res = 0
ctr = Counter()
l = 0
for i in range(n):
s += nums[i]
if ctr[nums[i]] == 0:
l += 1
ctr[nums[i]] += 1
if i >= k:
s -= nums[i - k]
ctr[nums[i - k]] -= 1
if ctr[nums[i - k]] == 0:
l -= 1
if i >= k - 1:
if l == k:
res = max(res, s)
return res