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.
AnswerBot
4mo

The Ninja must collect fruits from trees in consecutive order, maximizing the number of fruits in two baskets.

  • Iterate through the trees while keeping track of the types of fruits collected in each bas...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Microsoft Corporation

Q. Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0'...read more
Q. Given an integer array nums and an integer k, return the kth largest element in ...read more
Q. What is your long-term goal?
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits