-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkth-smallest-sum-subarray.cpp
77 lines (64 loc) · 1.4 KB
/
kth-smallest-sum-subarray.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
// CPP program to find k-th smallest sum
#include "algorithm"
#include "iostream"
#include "vector"
using namespace std;
int CalculateRank(vector<int> prefix, int n, int x)
{
int cnt;
// Initially rank is 0.
int rank = 0;
int sumBeforeIthindex = 0;
for (int i = 0; i < n; ++i) {
// Calculating the count the subarray with
// starting at ith index
cnt = upper_bound(prefix.begin(), prefix.end(),
sumBeforeIthindex + x) - prefix.begin();
// Subtracting the subarrays before ith index.
cnt -= i;
// Adding the count to rank.
rank += cnt;
sumBeforeIthindex = prefix[i];
}
return rank;
}
int findKthSmallestSum(int a[], int n, int k)
{
// PrefixSum array.
vector<int> prefix;
// Total Sum initially 0.
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += a[i];
prefix.push_back(sum);
}
// Binary search on possible
// range i.e [0, total sum]
int ans = 0;
int start = 0, end = sum;
while (start <= end) {
int mid = (start + end) >> 1;
// Calculating rank of the mid and
// comparing with K
if (CalculateRank(prefix, n, mid) >= k) {
// If greater or equal store the answer
ans = mid;
end = mid - 1;
}
else {
start = mid + 1;
}
}
return ans;
}
int main()
{
/// subarrays
/// [1],[2],[3],[1,2],[2,3],[1,2,3]
/// 1,2,3,3,5,6
int a[] = { 1, 2, 3 };
int k = 6;
int n = sizeof(a)/sizeof(a[0]);
cout << findKthSmallestSum(a, n, k);
return 0;
}