![]() |
VOOZH | about |
In a row of trees, the i-th tree produces fruit with type A[i]. We start at any tree of our choice, then repeatedly perform the following steps:
Note that we do not have any choice after the initial choice of starting tree: we must perform step 1, then step 2, then back to step 1, then step 2, and so on until we stop. we have two baskets, and each basket can carry any quantity of fruit, but we want each basket to only carry one type of fruit each. What is the Maximum amount of fruit we can collect with this procedure?
Examples:
Input: A[] = {1, 2, 3, 2, 2}
Output: 4
Explanation: We can collect {2, 3, 2, 2}. If we started at the first tree.Input: A[] = {1, 2, 1}
Output: 3
Explanation: We can collect {1,2,1}
Table of Content
The idea is to start at each tree one by one and try to collect fruits until you cannot put a fruit in either of your two baskets. For every starting position, we keep track of the types of fruits collected using a map or set. If a new fruit type appears and you already have two types in the baskets, you stop collecting. We calculate the total number of fruits collected for that starting tree, and repeat the process for all trees. Finally, we take the maximum among all starting positions.
4
The idea is to use a sliding window to keep track of the current sequence of trees containing at most two types of fruits.
This way, we scan the array only once, achieving a much more efficient solution than the naive approach.ll trees. Finally, we take the maximum among all starting positions.
4