Prateek and his Friends

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.

Example:

Input: n = 5, k = 12, arr[n] = {1, 3, 4, 5, 2}
Output: YES

Approach

C++

#include <bits/stdc++.h>
using namespace std;
bool subarray(int arr[], int nint sum)
{
    int currSum = arr[0], start = 0i;
    for (i = 1i <= ni++)
    {
        while (currSum > sum && start < i - 1)
        {
            currSum -= arr[start];
            start++;
        }
        if (currSum == sum)
            return true;
        if (i < n)
            currSum += arr[i];
    }
    return false;
}
int main()
{

    int n = 5k = 12;

    int arr[n] = {13452};

    bool ans = subarray(arrnk);
    if (ans == true)
        cout << "YES\n";
    else
        cout << "NO\n";

    return 0;
}


No comments:

Post a Comment