In this HackerEarth Prateek and his Friends problem solution, Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts is given in the array Value where an ith friend asks for a gift which has a cost Costi.

But, Prateek has only X amount of money to spend on gifts and he wants to invite his friends which are in the continuous range such that the sum of the cost of the gifts of those friends will be exactly equal to X.

If he can invite his friends, who can satisfy the above condition then, print YES otherwise print NO.


HackerEarth Prateek and his Friends problem solution


HackerEarth Prateek and his Friend's problem solution.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll Cost[1000005];
int main()
{

    freopen("si.txt","r",stdin);
    freopen("so.txt","w",stdout);
    int T;
    for(cin>>T;T;--T)
    {
        ll  N,X,START = 0,SUM;
        bool FLAG = false;
        cin>>N>>X;
        for(int i=0;i<N;i++)
        {
            cin>>Cost[i];
        }
        SUM = Cost[0];
        for(int i=1;i<N;i++)
        {

             while(SUM > X)
            {
                SUM -= Cost[START];
                START++;
            }

            if(SUM == X )
            {
                FLAG = true;
                break;
            }
            SUM += Cost[i];

        }
        while(SUM > X)
        {
            SUM -= Cost[START];
            START++;
        }
        if(SUM == X)
        {
            FLAG = true;
        }
        if(FLAG)
        {
            cout<<"YES"<<endl;
        }
        else
        {
            cout<<"NO"<<endl;
        }

    }

    return 0;
}


Second solution

t = int(raw_input())
for i in range(t):
    a = []
    n, s = map(int, raw_input().split())
    for j in range(n):
        a.append(int(raw_input()))
    start = 0;
    s1 = a[0]
    flag = False
    for j in range(1, n):
        while s1 > s:
            s1 -= a[start]
            start += 1
        if s1 == s:
            flag = True
            break
        s1 += a[j]
    while s1 > s:
        s1 -= a[start]
        start += 1
    if s1 == s:
        flag = True
    if flag:
        print "YES"
    else:
        print "NO"