This problem ate most of my time and not until a week after the contest did I realize my code wasn’t correct… So I lost 4 points which means I’ve only solved only 1 question in that weekly contest. Let’s dive right into this tricky but quite frankly easy problem.
fromcollectionsimportdefaultdict,dequeclassSolution:defmaximumSubarraySum(self,nums:List[int],k:int)->int:ifk>len(nums):return0window_dict=defaultdict(int)one_chr=set()max_sum=0local_sum=0foriinrange(len(nums)):# widow rightlocal_sum+=nums[i]window_dict[nums[i]]+=1one_chr.add(nums[i])# the right part needs to be placed before the left part# windoe leftifi>=k:local_sum-=nums[i-k]window_dict[nums[i-k]]-=1ifwindow_dict[nums[i-k]]!=1:ifnums[i-k]inone_chr:one_chr.remove(nums[i-k])iflen(one_chr)==k:iflocal_sum>max_sum:max_sum=local_sumreturnmax_sum# Failed at [9,9,9,1,2,3], k=3# output = 6, Expected = 12
fromcollectionsimportdefaultdict,dequeclassSolution:defmaximumSubarraySum(self,nums:List[int],k:int)->int:ifk>len(nums):return0window_dict=defaultdict(int)one_chr=set()max_sum=0local_sum=0foriinrange(len(nums)):# widow rightlocal_sum+=nums[i]window_dict[nums[i]]+=1one_chr.add(nums[i])# the right part needs to be placed before the left part# windoe leftifi>=k:local_sum-=nums[i-k]window_dict[nums[i-k]]-=1ifwindow_dict[nums[i-k]]==0:ifnums[i-k]inone_chr:one_chr.remove(nums[i-k])iflen(one_chr)==k:iflocal_sum>max_sum:max_sum=local_sumreturnmax_sum
Simply just to code out what happend when you faces different situs. I utilize the set() here to handle the window moving’s left part.
And use
if len(one_chr) == k:
if local_sum > max_sum:
max_sum = local_sum