Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int totalFruit(int[] fruits) {
- int first=fruits[0];
- int second =-1;
- int ans=1;
- int l=0;
- int r=0;
- for(int i=1;i<fruits.length;i++){
- if(fruits[i]==first || second==-1 || fruits[i]==second){
- if(fruits[i]!=first && second==-1)
- {
- second = fruits[i];
- }
- r++;
- ans=Math.max(ans, r-l+1);
- }else{
- int j=r;
- while(j>l && fruits[r]==fruits[j]){
- j--;
- }
- first=fruits[r];
- second=fruits[i];
- l=j+1;
- r=i;
- }
- }
- return ans;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment