Books (双指针)

时间:2022-07-28
本文章向大家介绍Books (双指针),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目描述

When Valera has got some free time, he goes to the library to read some books. Today he’s got t free minutes to read. That’s why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let’s number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.

Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn’t start reading the book if he doesn’t have enough free time to finish reading it.

Print the maximum number of books Valera can read.

思路

使用前后指针,从头到尾开始加,如果和超过k,就从j所在的位置开始删去,最后取最大值即可

代码

#include<bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e5+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int a[N];
void solve(){
    int n,t;cin>>n>>t;
    for(int i=0;i<n;i++) cin>>a[i];
    int ans=0;
    int sum=0;
    for(int i=0,j=0;i<n;i++){
        sum+=a[i];
        while(sum>t && j<n){
            sum-=a[j];
            j++;
        }
        ans=max(ans,i-j+1);
    }
    cout<<ans<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}