Find Maximum Candies With Two Types
Company: ByteDance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates algorithmic problem-solving with arrays, focusing on managing constraints on the number of distinct element types in a contiguous sequence and maintaining element frequency/state during a traversal.
Constraints
- 0 <= len(candies) <= 200000
- -1000000000 <= candies[i] <= 1000000000
Examples
Input: [1, 2, 1, 2, 3, 2, 2]
Expected Output: 4
Explanation: The longest valid segment is [1, 2, 1, 2], which has only two types and length 4.
Input: [0, 1, 2, 2]
Expected Output: 3
Explanation: The best segment is [1, 2, 2], which contains only types 1 and 2.
Hints
- Try maintaining a sliding window of consecutive candies that is always valid.
- Use a hash map to count how many candies of each type are currently inside the window, and shrink the left side when more than two types appear.