forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth-smallest-subarray-sum.cpp
More file actions
32 lines (30 loc) · 867 Bytes
/
kth-smallest-subarray-sum.cpp
File metadata and controls
32 lines (30 loc) · 867 Bytes
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
// Time: O(nlogr)
// Space: O(1)
class Solution {
public:
int kthSmallestSubarraySum(vector<int>& nums, int k) {
int left = *min_element(cbegin(nums), cend(nums));
int right = accumulate(cbegin(nums), cend(nums), 0);
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (check(nums, k, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
private:
bool check(const vector<int>& nums, int k, int x) {
int cnt = 0, curr = 0, left = 0;
for (int right = 0; right < size(nums); ++right) {
curr += nums[right];
while (curr > x) {
curr -= nums[left++];
}
cnt += right - left + 1;
}
return cnt >= k;
}
};