Thursday, 30 July 2015

HOTELS

Standard

Hotels Along the Croatian Coast

Link to the question :  HOTELS

HINT :

We apply the sliding concept. We start calculating the sum from index 0 of the array. If the sum exceeds the maximum amount given, we start subtracting  from sum from the beginning of the array, untill the sum becomes less than or equal to maximum amount.

SOURCE  CODE :


#include<stdio.h>
int main()
{
    int i, l;
    long long n, m, sum, max_sum;

    scanf("%lld%lld",&n, &m);

         int a[n];
        for(i=1; i<=n; i++)
        {
             scanf("%d", &a[i]);
        }
        l=1;
        max_sum = 0;
        sum = 0;
        for(i=1; i<=n; i++)
        {
            sum = sum + a[i];
            while(sum>m)
            {
                sum = sum - a[l];
                l++;
                if(max_sum<=sum && sum<=m)
                {
                    max_sum = sum;

                    break;
                }

            }
            if(max_sum<=sum && sum<=m)
            {
                max_sum = sum;

            }
        }
        printf("%lld\n", max_sum);

    return 0;
}

2 comments:

  1. Is there a need to break? while will itself end when sum<=m

    ReplyDelete