Sliding Window: Smallest sum of contiguous subarray

Problem Statement:

You are given an array and a value K.

You need to find the length of minimum sum subarray that is greater or equal to k.

Example:

Input: arr = [1, 2, 3, 4, 1] k = 7

Output: 2

Explanation: 

[3, 4] it is the minimal length.

Solution Explanation:

We will use sliding window approach to solve the problem.

Take 2 variables, l and r.

We will move the window towards the right until the sum is greater than k.

Now, move the left pointer untill sum < k.

Repeat the process, till you get the min sum.

Time Complexity: O(n)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <string>
#include <climits>
using namespace std;

int solution(int s, vector<int>& nums) 
{
    int left = 0, right = 0;
    int n = nums.size();
    int sum = 0;
    int result = INT_MAX;
    
    while (right < n) 
    {
        sum += nums[right++];
        
        while (sum >= s) 
        {
            result = min(result, right - left);
            sum -= nums[left++];
        }
    }
    return result == INT_MAX ? 0 : result;
}

int main()
{
    vector<int> arr = {1, 2, 3, 4, 1};
    int x = 7;

    cout << solution(x, arr);

    return 0;
}

Output

2
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *