Topics
Find the number of contiguous subarrays that sum up to at least given a sequence of integers of length , where each element is between and , and .
Idea
We use a sliding window where:
head
tries to expand right until window sum >= K (maintain window sum just below K)- All subarrays starting at
tail
and ending >=head
are valid (count = N - head - 1) tail
moves right to explore new starting positions
Time Complexity:
Space Complexity:
Code
bool check(ll x, ll sum, ll k) { return sum + x < k; }
void solve() {
int n;
ll k;
cin >> n >> k;
vector<ll> arr(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
ll sum = 0;
int tail = 0, head = -1;
ll ans = 0;
while (tail < n) {
while (head < n - 1 and check(arr[head + 1], sum, k)) {
head++;
sum += arr[head];
}
// process window
// [head+1 ...] contains all valid subarrays starting at tail
ans += (n - 1 - head);
if (tail <= head) {
sum -= arr[tail];
}
tail++;
head = max(head, tail - 1);
}
cout << ans << endl;
}
Related