-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_862_ShortestSubArrayWithSumAtLeastK.cpp
88 lines (77 loc) · 2.1 KB
/
LC_862_ShortestSubArrayWithSumAtLeastK.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/
862. Shortest Subarray with Sum at Least K
*/
class Solution {
public:
int shortestSubarray_TLE(vector<int>& nums, int k) {
int i=0, j=0;
int cursum =0 ;
int len=INT_MAX;
while(j<nums.size())
{
cursum += nums[j];
int left = i, delsum = cursum;
while(left < j)
{
delsum -= nums[left];
left++;
if(delsum >= k)
{
cursum = delsum;
i=left;
}
}
while(cursum>=k)
{
len = min(len, j-i+1);
cursum -= nums[i];
// cout<<cursum<<" ";
i++;
}
j++;
}
return len == INT_MAX ? -1: len;
}
int shortestSubarray(vector<int>& nums, int k) {
int n = nums.size();
int len = INT_MAX;
deque<int> dq;
vector<long> ps(n, 0);
ps[0] = nums[0];
// cout<<ps[0]<<" ";
for(int i=1; i<n; i++)
{
ps[i] = ps[i-1] + nums[i];
// cout<<ps[i]<<" ";
}
// cout<<"\n";
for(int i=1; i<n; i++)
{
if(ps[i] >= k)
len = min(len, i+1);
// cout<<i<<" ";
// showdq(dq);
while(!dq.empty() && ps[i] - ps[dq.front()] >= k)
{
len = min(len, i-dq.front());
dq.pop_front();
}
// cout << '\t';
// showdq(dq);
while(!dq.empty() && ps[i]<=ps[dq.back()])
dq.pop_back();
dq.push_back(i);
// cout << '\t';
// showdq(dq);
// cout << '\n';
}
return len == INT_MAX ? -1: len;
}
void showdq(deque<int> g)
{
deque<int>::iterator it;
for (it = g.begin(); it != g.end(); ++it)
cout << ' ' << *it;
}
};