tabish527112

fruit into baskets

Jan 9th, 2022
794
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. class Solution {
  2.     public int totalFruit(int[] fruits) {
  3.         int first=fruits[0];
  4.         int second =-1;
  5.  
  6.         int ans=1;
  7.         int l=0;
  8.         int r=0;
  9.         for(int i=1;i<fruits.length;i++){
  10.             if(fruits[i]==first || second==-1 || fruits[i]==second){
  11.                 if(fruits[i]!=first && second==-1)
  12.                 {
  13.                     second = fruits[i];
  14.                 }
  15.                 r++;
  16.                 ans=Math.max(ans, r-l+1);
  17.             }else{
  18.                 int j=r;
  19.                 while(j>l && fruits[r]==fruits[j]){
  20.                     j--;
  21.                 }
  22.  
  23.                 first=fruits[r];
  24.                 second=fruits[i];
  25.                
  26.                 l=j+1;
  27.                 r=i;
  28.             }
  29.         }
  30.         return ans;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment