Fruits into Baskets (medium)

刷题参考: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;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值