Fruit Into Baskets in C++


Suppose we have a row of trees, the i-th tree produces fruit with type tree[i]. we can start at any tree of our choice, then repeatedly perform these steps −

  • Add one piece of fruit from this tree to our baskets. If there is no chance, then stop.
  • Move to the next tree to the right of the current one. If there is no tree to the right, then stop.

We have two baskets, and each basket can carry any quantity of fruit, but we want each basket should only carry one type of fruit each. We have to find the total amount of fruit that we can collect with this procedure? So if the trees are like [0, 1, 2, 2], then the output will be 3. We can collect [1,2,2], if we start from the first tree, then we would only collect [0, 1]

To solve this, we will follow these steps −

  • n := tree size, j := 0, ans := 0
  • create one map m
  • for i in range 0 to n – 1
    • increase m[tree[i]] by 1
    • while size of m is > 2 and j <= i, then
      • decrease m[tree[j]] by 1
      • if m[tree[j]] = 0, then delete tree[j] from m
      • increase j by 1
    • ans := max of i – j + 1 and ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int totalFruit(vector<int>& tree) {
      int n = tree.size();
      int j = 0;
      map <int, int> m;
      int ans = 0;
      for(int i = 0; i < n; i++){
         m[tree[i]] += 1;
         while(m.size() > 2 && j <= i){
            m[tree[j]]--;
            if(m[tree[j]] == 0)m.erase(tree[j]);
            j++;
         }
         ans = max(i - j + 1, ans);
      }
      return ans;
   }
};
main(){
   vector<int> v = {3,3,3,1,2,1,1,2,3,3,4};
   Solution ob;
   cout <<(ob.totalFruit(v));
}

Input

[3,3,3,1,2,1,1,2,3,3,4]

Output

5

Updated on: 30-Apr-2020

753 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements