Smallest Subarray
Given an array of integers and a number x, find the smallest subarray with a sum greater than the given value. The input will have the array and the number separated by a comma.
Sample Input -
[1, 4, 45, 6, 0, 19], 51
Sample Output -
3
Solution in C++
#include<iostream>
#include<vector>
int findSmallestSubarray(const std::vector& arr, int x) {
int n = arr.size();
int min_len = n + 1;
int curr_sum = 0;
int start = 0;
for (int i = 0; i < n; i++) {
curr_sum += arr[i];
while (curr_sum > x && start <= i) {
min_len = std::min(min_len, i - start + 1);
curr_sum -= arr[start];
start++;
}
}
if (min_len == n + 1) {
return -1;
}
return min_len;
}
int main() {
std::vector arr = {1, 4, 45, 6, 0, 19};
int x = 51;
int len = findSmallestSubarray(arr, x);
if (len == -1) {
std::cout << "No subarray found with sum greater than " << x << std::endl;
} else {
std::cout << "Smallest subarray with sum greater than " << x << " has length " << len << std::endl;
}
return 0;
}

0 Comments