刷题参考:https://blog.csdn.net/IBelieve2016/article/details/104544763
/*
In a row of trees, the `i`-th tree produces fruit with type `tree[i]`.
You start at any tree of your choice, then repeatedly perform the following steps:
Add one piece of fruit from this tree to your baskets. If you cannot, stop.
Move to the next tree to the right of the current tree. If there is no tree to the right, stop.
Note that you do not have any choice after the initial choice of starting tree: you must perform
step 1, then step 2, then back to step 1, then step 2, and so on until you stop.
You have two baskets, and each basket can carry any quantity of fruit,
but you want each basket to only carry one type of fruit each.
What is the total amount of fruit you can collect with this procedure?
收集2种不同水果,从当前一排树选择一个子序列 树集,能够收集最多的水果的序列。
类似:[Longest Substring with At Most Two Distinct Characters]
*/
#include<iostream>
#include<vector>
using namespace std;
//T:O(n),V:O(1)
int solution(vector<int>nums){
int a=0,b=0;//a:左边的元素,b:在a右边的元素
int cntB=0;//连续b的个数,用于确定下一轮序列的长度
int count=0;//统计当前序列个数
int res=0;//保存最大值
for(int i=0;i<nums.size();i++){
//统计序列个数
if(nums[i]==a||nums[i]==b){
count++;
}else{
//新元素i不等于a,b,则需要调整为a=b,b=i,且当前的长度为cntB+1
count=cntB+1;
}
//处理右边b的情况,
//一旦当前值和右边b的值不同,就需要随时更换右边的值和位置以及确定右边的长度
if(nums[i]==b){
//连续的b值,则个数加1
cntB++;
}else{
//非连续,调整位置,重置右边的连续个数为1
a=b;
b=nums[i];
cntB=1;
}
//最大值
res=max(res,count);
}
return res;
}
int main(){
vector<int>nums{3,3,3,1,2,1,1,2,3,3,4};
cout<<solution(nums);
return 0;
}