0

The problem is from a recent competition on Codechef. According to the problem, for a given array of length N, find the maximum average of the numbers of any contiguous sub-array of length between A and B.

Now here is the logic that I have used. I have in a loop iterated over the possible contiguous sub-array length K from A to B. Then for every such K, I have used the sliding window mechanism to find the maximum sum of contiguous elements of the array. Then I check if the already stored answer (the average) is smaller than the current maximum/K and update the answer.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    { 
        int n,b,a;
        cin>>n>>b>>a;
        long long arr[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>arr[i];
        }
        double ans=0;
        for(int k=a;k<=b;k++)
        {
            long long maxi=0;
            for(int i=1;i<=k;i++)
            {
                maxi=maxi+arr[i];
            }
            long long l=maxi;
            for(int i=k+1;i<=n;i++)
            {
                l=l+arr[i]-arr[i-k];
                maxi=max(maxi,l);
            }
            double x=(double)(((double)(maxi))/(double)(k));
            ans=max(ans,x);
        }
        cout<<ans<<endl;
    }
}

However, after implementing my logic over as shown, I am getting wrong answers even though I do not know how different they are the actual answer since I have not obtained anything wrong in my processes of debugging.

The following is an edit: Are my previous code and the following the same?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,b,a;
        cin>>n>>b>>a;
        long long arr[n+1];
        for(int i=1;i<=n;i++)
        {
            cin>>arr[i];
        }
        long double ans=0;
        for(int k=a;k<=b;k++)
        {
            long long l=0;
            for(int i=1;i<=k;i++)
            {
                l=l+arr[i];
            }
            ans=max(ans,(long double)(((long double)(l))/(long double)(k)));
            for(int i=k+1;i<=n;i++)
            {
                l=l+arr[i]-arr[i-k];
                ans=max(ans,(long double)(((long double)(l))/(long double)(k)));
            }
        }
        cout<<ans<<endl;
    }
}
Arjo
  • 103
  • 4
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/186987/discussion-on-question-by-al-a-why-is-my-sliding-window-algorithm-not-providin). – Bhargav Rao Jan 20 '19 at 05:08

1 Answers1

0

Thanks for helping guys. I tried out the following and it sort of works:

cout<<fixed<<setprecision(10);

setprecision(10)

Arjo
  • 103
  • 4