Skip to content

Commit e200917

Browse files
authored
Create Shortest Subarray with Sum at least K.cpp
1 parent 58c106c commit e200917

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: Shortest Subarray with Sum at least K.cpp

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
3+
If there is no non-empty subarray with sum at least K, return -1.
4+
5+
Input: A = [2,-1,2], K = 3
6+
Output: 3
7+
8+
*/
9+
10+
11+
#include<bits/stdc++.h>
12+
13+
using namespace std;
14+
15+
int shortestSubarray(vector<int>& A, int K)
16+
{
17+
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq; // min heap to store the length and sum of the subarray
18+
int sum = 0;
19+
int ans = INT_MAX;
20+
for(int i=0;i<A.size();i++){
21+
sum += A[i];
22+
if(sum >= K){
23+
ans = min(ans,i+1);
24+
}
25+
while(pq.size() >0 && sum-pq.top().first >=K ){
26+
ans = min(ans,i-pq.top().second);
27+
pq.pop();
28+
}
29+
pq.push({sum,i});
30+
}
31+
return ans == INT_MAX ? -1 : ans;
32+
}
33+
34+
int main()
35+
{
36+
int K;
37+
cin >> K;
38+
cout << "Enter the number of elements in the array" ;
39+
int n;
40+
cin >> n;
41+
vector<int> arr(n);
42+
for(int i=0;i<n;i++)
43+
{
44+
int x;
45+
cin >> x;
46+
arr.push_back(x);
47+
}
48+
49+
cout << shortestSubarray(arr , K);
50+
51+
return 0;
52+
}
53+
54+
55+
56+
57+

0 commit comments

Comments
 (0)