10. Max Subarray sum of positive no <= k

Solution : (Sliding Window)

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;

    vector<int> v;
    for (int i = 1; i <= n; i++)
    {
        int a;
        cin >> a;
        v.push_back(a);
    }

    int sum = 0;
    int start = 0;
    int maxSum = INT_MIN;

    for (int i = 0; i < v.size(); i++)
    {
        sum = sum + v[i];
        if (sum <= m)
        {
            if (sum > maxSum)
            {
                maxSum = sum;
            }
        }

        while (sum > m && start < i)
        {
            sum = sum - v[start];
            start++;
            if (sum <= m)
            {
                if (sum > maxSum)
                {
                    maxSum = sum;
                }
            }
        }
    }
    cout << maxSum;
    return 0;
}

Last updated