#include<bits/stdc++.h>
#define endl '\n'
using ll = long long;
using namespace std;
const int N = 3e5 + 9;
struct Segment_Tree {
ll t[4 * N];
auto merge(auto &l, auto &r) { // <= Change this function
return max(l, r);
}
void build(int node, int st, int en, vector<ll> &arr) { //=> O(N)
if (st == en) {
t[node] = arr[st];
return;
}
int mid = (st + en) >> 1;
build(node << 1, st, mid, arr); // divide left side
build(node << 1 | 1, mid + 1, en, arr); // divide right side
// Merging left and right portion
auto &Cur = t[node];
auto &Left = t[node << 1];
auto &Right = t[node << 1 | 1];
Cur = merge(Left, Right);
return;
}
ll query(int node, int st, int en, int l, int r) { //=> O(log n)
if (st > r || en < l) { // No overlapping and out of range
return INT_MIN; // <== careful
}
if (l <= st && en <= r) { // Complete overlapped (l-r in range)
return t[node];
}
// Partial overlapping
int mid = (st + en) >> 1;
auto Left = query(node << 1, st, mid, l, r);
auto Right = query(node << 1 | 1, mid + 1, en, l, r);
return merge(Left, Right);
}
} st;
struct Segment_Tree1 {
ll t[4 * N];
auto merge(auto &l, auto &r) { // <= Change this function
return min(l, r);
}
void build(int node, int st, int en, vector<ll> &arr) { //=> O(N)
if (st == en) {
t[node] = arr[st];
return;
}
int mid = (st + en) >> 1;
build(node << 1, st, mid, arr); // divide left side
build(node << 1 | 1, mid + 1, en, arr); // divide right side
// Merging left and right portion
auto &Cur = t[node];
auto &Left = t[node << 1];
auto &Right = t[node << 1 | 1];
Cur = merge(Left, Right);
return;
}
ll query(int node, int st, int en, int l, int r) { //=> O(log n)
if (st > r || en < l) { // No overlapping and out of range
return INT_MAX; // <== careful
}
if (l <= st && en <= r) { // Complete overlapped (l-r in range)
return t[node];
}
// Partial overlapping
int mid = (st + en) >> 1;
auto Left = query(node << 1, st, mid, l, r);
auto Right = query(node << 1 | 1, mid + 1, en, l, r);
return merge(Left, Right);
}
} st1;
void solve() {
ll n, m;
cin >> n >> m;
vector<ll> v(n + 1), pre(n + 1);
for (int i = 1; i <= n; i++) {
ll x; cin >> x;
v[i] = x;
pre[i] = x;
pre[i] += pre[i - 1];
}
st.build(1, 1, n, v); // Creating Segment tree;
st1.build(1, 1, n, v);
ll ans = 1e9;
for(int i = 1; i + m - 1 <= n; i++){
ll ans1 = pre[i + m - 1] - pre[i - 1];
ll midMax = st.query(1, 1, n, i, i + m - 1);
ll leftMn = 1e9, rightMn = 1e9;
if(i != 1){
leftMn = st1.query(1, 1, n, 1, i - 1);
}
if(i != n){
rightMn = st1.query(1, 1, n, i + m, n);
}
ll ans2 = ans1 - midMax + leftMn;
ll ans3 = ans1 - midMax + rightMn;
ans = min({ans, ans1, ans2, ans3});
}
cout << ans << endl;
return;
}
int main() {
ios::sync_with_stdio(false);cin.tie(0), cin.tie(0);
int tc = 1;
cin >> tc;
for (int i = 1; i <= tc; ++i) {
// cout << "Case " << i << ":\n";
solve();
}
return 0;
}