Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created December 25, 2020 05:44
Show Gist options
  • Save codecakes/430e36d78fa86235619e5d2b330f03a1 to your computer and use it in GitHub Desktop.
Save codecakes/430e36d78fa86235619e5d2b330f03a1 to your computer and use it in GitHub Desktop.
Find K maximum occurrences in unique K baskets until more than K distinct occurrences
from collections import Counter
def fruits_into_baskets(fruits):
max_ctr = Counter()
left_idx = 0
distinct = 0
max_k = 2
ct = float('-inf')
for right_idx, r_char in enumerate(fruits):
if not max_ctr[r_char]:
distinct += 1
max_ctr[r_char] += 1
while distinct > max_k:
l_char = fruits[left_idx]
if max_ctr[l_char]:
max_ctr[l_char] -= 1
if not max_ctr[l_char]:
distinct -= 1
left_idx += 1
ct = max(ct, sum(v for _, v in max_ctr.most_common(2)))
return ct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment