-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1918-kth-smallest-subarray-sum.js
More file actions
51 lines (42 loc) · 1.16 KB
/
1918-kth-smallest-subarray-sum.js
File metadata and controls
51 lines (42 loc) · 1.16 KB
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
/**
* 1918. Kth Smallest Subarray Sum
* https://leetcode.com/problems/kth-smallest-subarray-sum/
* Difficulty: Medium
*
* Given an integer array nums of length n and an integer k, return the kth smallest subarray sum.
*
* A subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray
* sum is the sum of all elements in the subarray.
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var kthSmallestSubarraySum = function(nums, k) {
let result = Math.min(...nums);
let maxSum = nums.reduce((sum, num) => sum + num, 0);
while (result < maxSum) {
const midSum = Math.floor((result + maxSum) / 2);
if (countSubarraysWithSumLessOrEqual(midSum) < k) {
result = midSum + 1;
} else {
maxSum = midSum;
}
}
return result;
function countSubarraysWithSumLessOrEqual(target) {
let count = 0;
let left = 0;
let currentSum = 0;
for (let right = 0; right < nums.length; right++) {
currentSum += nums[right];
while (currentSum > target) {
currentSum -= nums[left];
left++;
}
count += right - left + 1;
}
return count;
}
};