File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(nlogr)
2
+ // Space: O(1)
3
+
4
+ class Solution {
5
+ public:
6
+ int kthSmallestSubarraySum (vector<int >& nums, int k) {
7
+ int left = *min_element (cbegin (nums), cend (nums));
8
+ int right = accumulate (cbegin (nums), cend (nums), 0 );
9
+ while (left <= right) {
10
+ const auto & mid = left + (right - left) / 2 ;
11
+ if (check (nums, k, mid)) {
12
+ right = mid - 1 ;
13
+ } else {
14
+ left = mid + 1 ;
15
+ }
16
+ }
17
+ return left;
18
+ }
19
+
20
+ private:
21
+ bool check (const vector<int >& nums, int k, int x) {
22
+ int cnt = 0 , curr = 0 , left = 0 ;
23
+ for (int right = 0 ; right < size (nums); ++right) {
24
+ curr += nums[right];
25
+ while (curr > x) {
26
+ curr -= nums[left++];
27
+ }
28
+ cnt += right - left + 1 ;
29
+ }
30
+ return cnt >= k;
31
+ }
32
+ };
You can’t perform that action at this time.
0 commit comments