Muffin Selection (muffin) 50/100

please help me. for this problem I get 50 out of 100 points.

#include <iostream>
using namespace std;
int t[1000001],n,k;
long long sv=0,sn=0;
int main()
{
    cin>>n>>k;
    for(int i=1;i<=n;++i)
        cin>>t[i];
    for(int i=0;i<k;++i)
        sv+=t[i];
    for(int i=1;i<=n-k+1;++i)
    {
        sn=0;
        for(int j=i;j<i+k;++j)
        {
            sn+=t[j];
        }
        if(sn>sv)
            sv=sn;
    }
    cout<<sv;
    return 0;
}

Your code is too slow. Try to think: is there a way to get the sum of muffins from a to (a+K-1) in constant time if you know the sum from (a-1) to (a+K-2)?

1 Mi Piace

Intervals (a,b) and (a+1,b+1) share most of their elements, so once you’ve checked the former, do you really need to iterate through the latter?