Katkat

Find Maximum Candies With Two Types

ByteDanceSoftware Engineer · Onsite

Last updated

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.

You are given a row of candies represented by an array candies, where candies[i] is the type of the candy at position i.

You may choose any starting position and then move only to the right, taking every candy you encounter. However, you can carry candies of at most two distinct types. Once you encounter a candy of a third distinct type, you must stop before taking it.

Return the maximum number of candies you can take.

Example:

Input: candies = [1, 2, 1, 2, 3, 2, 2]
Output: 4
Explanation: Starting at index 0, you can take [1, 2, 1, 2]. The next candy has type 3, which would be a third type, so you must stop.

Follow-up: Solve it in linear time.