Dashboard Temp Share Shortlinks Frames API

HTMLify

Longest subarray with Atmost two distinct integers
Views: 5 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def totalElements(self, arr):
        left = 0
        max_len = 0
        freq = {}
        distinct = 0
        
        for right in range(len(arr)):
            if arr[right] not in freq or freq[arr[right]] == 0:
                distinct += 1
            
            freq[arr[right]] = freq.get(arr[right], 0) + 1
            
            while distinct > 2:
                freq[arr[left]] -= 1
                if freq[arr[left]] == 0:
                    distinct -= 1
                left += 1
            
            max_len = max(max_len, right - left + 1)
        
        return max_len