Skip to content

Commit 535eff3

Browse files
committed
Given an array of integers (A[]) and a number x, find the smallest subarray with sum greater than the given value.
1 parent 0e9c209 commit 535eff3

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
- [Triplet Sum in Array](https://practice.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1# "view question") - [Cpp Solution](./solutions/Triplet%20Sum%20in%20Array.cpp)
3232
- [Trapping Rain Water](https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1# "view question") - [Cpp Solution](./solutions/Trapping%20Rain%20Water.cpp)
3333
- [Chocolate Distribution Problem](https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem/0# "view question") - [Cpp Solution](./solutions/Chocolate%20Distribution%20Problem.cpp)
34+
- [Smallest subarray with sum greater than x](https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x5651/1# "view question") - [Cpp Solution](./solutions/Smallest%20subarray%20with%20sum%20greater%20than%20x.cpp)
3435
- []( "view question") - [Cpp Solution](./solutions/.cpp)
3536

3637
<!-- - []( "view question") - [Cpp Solution](./solutions/) -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
Smallest subarray with sum greater than x
3+
==========================================
4+
5+
Given an array of integers (A[]) and a number x, find the smallest subarray with sum greater than the given value.
6+
7+
Note: The answer always exists. It is guaranteed that x doesn't exceed the summation of a[i] (from 1 to N).
8+
9+
Example 1:
10+
Input:
11+
A[] = {1, 4, 45, 6, 0, 19}
12+
x = 51
13+
Output: 3
14+
Explanation:
15+
Minimum length subarray is
16+
{4, 45, 6}
17+
18+
Example 2:
19+
Input:
20+
A[] = {1, 10, 5, 2, 7}
21+
x = 9
22+
Output: 1
23+
Explanation:
24+
Minimum length subarray is {10}
25+
26+
Your Task:
27+
You don't need to read input or print anything. Your task is to complete the function sb() which takes the array A[], its size N and an integer X as inputs and returns the required ouput.
28+
29+
Expected Time Complexity: O(N)
30+
Expected Auxiliary Space: O(1)
31+
32+
Constraints:
33+
1 ≤ N, x ≤ 105
34+
1 ≤ A[] ≤ 104
35+
*/
36+
37+
int sb(int arr[], int n, int x)
38+
{
39+
int curr_sum = 0, min_len = n + 1;
40+
int start = 0, end = 0;
41+
42+
while (end < n)
43+
{
44+
while (curr_sum <= x && end < n)
45+
{
46+
curr_sum += arr[end];
47+
end++;
48+
}
49+
50+
while (curr_sum > x && start < n)
51+
{
52+
min_len = min(min_len, end - start);
53+
curr_sum -= arr[start];
54+
start++;
55+
}
56+
}
57+
return min_len;
58+
}

0 commit comments

Comments
 (0)