Fruits and Baskets Problem Statement

You are given 'n' fruit trees planted along a road, numbered from 0 to n-1. Each tree bears a fruit type represented by an uppercase English alphabet. A Ninja walking along this road has two baskets. The goal is to collect the maximum number of fruits in these baskets, with the restriction that each basket can hold only one type of fruit.

The Ninja can start picking fruits from any tree and must continue picking from consecutive trees. Once he starts, he cannot skip any tree, and he must stop collecting when he encounters a third different type of fruit since both baskets can only hold two different fruit types.

Your task is to determine the maximum number of fruits the Ninja can collect in both baskets given the above conditions.

Input:

The first line of input contains an integer 'T' denoting the number of test cases.
The next '2*T' lines represent the 'T' test cases.
The first line of each test case contains an integer 'n', representing the number of trees.
The second line of the test case contains a string consisting of the 'n' uppercase characters of the English alphabet that represent the type of fruit in each tree.

Output:

For each test case, output on a separate line, the maximum number of fruits the Ninja can collect in both baskets after satisfying all the given conditions.

Example:

Input:
T = 1
n = 3
str = "ABB"
Output:
3

Constraints:

  • 1 <= T <= 50
  • 1 <= n <= 10^4
  • Time limit: 1 sec
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Be the first one to answer
Add answer anonymously...
Microsoft Corporation Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter