/*************************BALIGA***************************************/
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define lli long long int
#define ulli unsigned long long int
#define lld long double
#define MP make_pair
#define PB push_back
#define MT make_tuple
#define rep0(i,n) for(lli i=0;i<n;i++)
#define rep1(i,n) for(lli i=1;i<=n;i++)
#define rep(i,x,y) for(lli i=x;i<=y;i++)
#define per1(i,n) for(lli i=n;i>0;i--)
#define per0(i,n) for(lli i=n-1;i>=0;i--)
#define per(i,x,y) for(lli i=x;i>=y;i--)
#define ff first
#define ss second
#define pli pair <lli,lli>
#define plli pair <pli,lli>
#define vi vector<int>
#define vli vector<long long int>
#define vs vector<string>
#define vc vector<char>
#define vipair vector<pair<int,int>>
#define vlipair vector<pair<lli,lli>>
#define all(c) c.begin(),c.end()
#define print(c) for(lli i=0;i<c.size();i++) cout<<c[i]<<' '
#define max3(a,b,c) max(max(a,b),c)
#define min3(a,b,c) min(min(a,b),c)
#define INF64 1e18
#define INF32 1e9
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const lli mod = 1e9+7;
const lld eps = 1e-9;
const lli maxn = 1e5+10;
const lli max_nodes=15;
const lli alpha=26;
const lli max_log=18;
lli fact[maxn+3];
template <typename T> void add(T &a, T b){a += b;if(a >= mod)a -= mod;}
template <typename T> void sub(T &a, T b){a -= b;if(a < 0)a += mod;}
template <typename T> void mul(T &a, T b){a *= b;if(a >= mod)a %= mod;}
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
void calcfac() {fact[0]=1;fact[1]=1;rep(i,2,maxn) fact[i] = (fact[i-1]*i)%mod;}
lli gcd(lli a,lli b) {if(b==0) return a; return gcd(b,a%b);}
lli fastexp(lli a,lli b) {a%=mod;lli res=1;while(b>0){if(b&1) res=(res*a)%mod; a=(a*a)%mod; b>>=1;}return res;}
lli inverse(lli n) {return fastexp(n,mod-2);}
lli ncr(lli n , lli r){if(n < r|| (n < 0) || (r < 0)) return 0 ; return (((fact[n] * inverse(fact[r]))%mod)*inverse(fact[n-r]))%mod;}
int pct(int x) { return __builtin_popcount(x);} //number of set bits
int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
// TRIE
// int triex[max_nodes][alpha],globcount=1;
// void build_triex(string s) {int i = 0, v = 0;while(i < s.size()){if(triex[v][s[i]-'a'] == -1)v = triex[v][s[i++]-'a'] = globcount++ ;else v = triex[v][s[i++]-'a'];}}
// SPARSE TABLE
// lli logarithm[maxn+1];
// void calclog() {logarithm[1]=0;for(lli i=2;i<=maxn;i++)logarithm[i]=logarithm[i/2]+1;}
// lli sp_table[maxn][max_log+1];
// void build_sp(vli &nums) {calclog();lli n=nums.size();rep0(i,n)sp_table[i][0]=nums[i];for(lli j=1;j<=max_log;j++){for(lli i=0;i+(1<<j)<=n;i++){sp_table[i][j]=min(sp_table[i][j-1],sp_table[i+(1<<(j-1))][j-1]);}}}
// lli query_sp(lli l,lli r) {lli j=logarithm[r-l+1];return min(sp_table[l][j],sp_table[r-(1<<j)+1][j]);}
vli vis(maxn+10,0);
lli ans=0;

void dfs(lli u,vector<vli> &adj, vli &vals, map<lli,lli> &mp) {
	vis[u]=1;
	map<lli,lli> np;
	for(auto m:mp) {
		np[gcd(m.first,vals[u])] = m.second;
	}
	np[vals[u]]++;
	// mp.clear();
	for(auto m:np) {
		ans = (ans+((m.second*m.first)%mod))%mod;
	}
	for(lli v: adj[u]) {
		if(vis[v]) continue;
		else dfs(v,adj,vals,np);
	}
}

void solve() {
	lli n;
	cin>>n;
	vli nums(n+1);
	rep1(i,n) cin>>nums[i];
	vector<vli > adj(n+1,vli(0));
	lli u,v;
	rep0(i,n-1) {
		cin>>u>>v;
		adj[u].PB(v);
		adj[v].PB(u);
	}
	map<lli,lli> mp;
	dfs(1,adj,nums,mp);
	cout<<ans;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int TC;
    TC=1;
    // cin>>TC;
    for(int t=0;t<TC;t++) solve();
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}


/*************************BALIGA***************************************/
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define lli long long int
#define ulli unsigned long long int
#define lld long double
#define MP make_pair
#define PB push_back
#define MT make_tuple
#define rep0(i,n) for(lli i=0;i<n;i++)
#define rep1(i,n) for(lli i=1;i<=n;i++)
#define rep(i,x,y) for(lli i=x;i<=y;i++)
#define per1(i,n) for(lli i=n;i>0;i--)
#define per0(i,n) for(lli i=n-1;i>=0;i--)
#define per(i,x,y) for(lli i=x;i>=y;i--)
#define ff first
#define ss second
#define pli pair <lli,lli>
#define plli pair <pli,lli>
#define vi vector<int>
#define vli vector<long long int>
#define vs vector<string>
#define vc vector<char>
#define vipair vector<pair<int,int>>
#define vlipair vector<pair<lli,lli>>
#define all(c) c.begin(),c.end()
#define print(c) for(lli i=0;i<c.size();i++) cout<<c[i]<<' '
#define max3(a,b,c) max(max(a,b),c)
#define min3(a,b,c) min(min(a,b),c)
#define INF64 1e18
#define INF32 1e9
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const lli mod = 1e9+7;
const lld eps = 1e-9;
const lli maxn = 1e5+10;
const lli max_nodes=15;
const lli alpha=26;
const lli max_log=18;
lli fact[maxn+3];
template <typename T> void add(T &a, T b){a += b;if(a >= mod)a -= mod;}
template <typename T> void sub(T &a, T b){a -= b;if(a < 0)a += mod;}
template <typename T> void mul(T &a, T b){a *= b;if(a >= mod)a %= mod;}
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
void calcfac() {fact[0]=1;fact[1]=1;rep(i,2,maxn) fact[i] = (fact[i-1]*i)%mod;}
lli gcd(lli a,lli b) {if(b==0) return a; return gcd(b,a%b);}
lli fastexp(lli a,lli b) {a%=mod;lli res=1;while(b>0){if(b&1) res=(res*a)%mod; a=(a*a)%mod; b>>=1;}return res;}
lli inverse(lli n) {return fastexp(n,mod-2);}
lli ncr(lli n , lli r){if(n < r|| (n < 0) || (r < 0)) return 0 ; return (((fact[n] * inverse(fact[r]))%mod)*inverse(fact[n-r]))%mod;}
int pct(int x) { return __builtin_popcount(x);} //number of set bits
int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
// TRIE
// int triex[max_nodes][alpha],globcount=1;
// void build_triex(string s) {int i = 0, v = 0;while(i < s.size()){if(triex[v][s[i]-'a'] == -1)v = triex[v][s[i++]-'a'] = globcount++ ;else v = triex[v][s[i++]-'a'];}}
// SPARSE TABLE
// lli logarithm[maxn+1];
// void calclog() {logarithm[1]=0;for(lli i=2;i<=maxn;i++)logarithm[i]=logarithm[i/2]+1;}
// lli sp_table[maxn][max_log+1];
// void build_sp(vli &nums) {calclog();lli n=nums.size();rep0(i,n)sp_table[i][0]=nums[i];for(lli j=1;j<=max_log;j++){for(lli i=0;i+(1<<j)<=n;i++){sp_table[i][j]=min(sp_table[i][j-1],sp_table[i+(1<<(j-1))][j-1]);}}}
// lli query_sp(lli l,lli r) {lli j=logarithm[r-l+1];return min(sp_table[l][j],sp_table[r-(1<<j)+1][j]);}
vli vis(maxn+10,0);
lli ans=0;

void dfs(lli u,vector<vli> &adj, vli &vals, map<lli,lli> &mp) {
	vis[u]=1;
	map<lli,lli> np;
	for(auto m:mp) {
		np[gcd(m.first,vals[u])] += m.second;
	}
	np[vals[u]]++;
	// mp.clear();
	for(auto m:np) {
		ans = (ans+((m.second*m.first)%mod))%mod;
	}
	for(lli v: adj[u]) {
		if(vis[v]) continue;
		else dfs(v,adj,vals,np);
	}
}

void solve() {
	lli n;
	cin>>n;
	vli nums(n+1);
	rep1(i,n) cin>>nums[i];
	vector<vli > adj(n+1,vli(0));
	lli u,v;
	rep0(i,n-1) {
		cin>>u>>v;
		adj[u].PB(v);
		adj[v].PB(u);
	}
	map<lli,lli> mp;
	dfs(1,adj,nums,mp);
	cout<<ans;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int TC;
    TC=1;
    // cin>>TC;
    for(int t=0;t<TC;t++) solve();
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;
const int L = ceil(log2(N)) + 3;
const long long M = 1e9 + 7;

int n;
int depth[N];
int up[N][L];
int tin[N], tout[N], tim;
vector<int> g[N];
long long ans;
long long x[N];
long long fpb[N][L];

void dfs(int u, int p, int h) {
  depth[u] = h;
  up[u][0] = p;
  fpb[u][0] = __gcd(x[u], x[p]);
  tin[u] = ++tim;
  for (int i = 1; i < L; i++) {
    up[u][i] = up[up[u][i - 1]][i - 1];
    fpb[u][i] = __gcd(fpb[u][i - 1], fpb[up[u][i - 1]][i - 1]);
  }
  for (auto v : g[u]) {
    if (v == p) continue;
    dfs(v, u, h + 1);
  }
  tout[u] = ++tim;
}

bool is_anc(int u, int v) {
  return (tin[u] <= tin[v] && tout[u] >= tout[v]);
}

int lca(int u, int v) {
  if (is_anc(u, v)) return u;
  if (is_anc(v, u)) return v;
  for (int i = L - 1; i >= 0; i--) {
    if (!is_anc(up[u][i], v)) {
      u = up[u][i];
    }
  }
  return up[u][0];
}

long long getGcd(int u, int h) {
  long long ret = x[u];
  for (int i = L - 1; i >= 0; i--) {
    if (depth[up[u][i]] >= h) {
      ret = __gcd(ret, fpb[u][i]);
      u = up[u][i];
    }
  }
  return ret;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 1, 0);
  for (int i = 1; i <= n; i++) {
    int dist = 0;
    while (dist <= depth[i]) {
      long long curGcd = getGcd(i, dist);
      int l = dist, r = depth[i], at = dist;
      while (l <= r) {
        int mid = (l + r) >> 1;
        if (getGcd(i, mid) == curGcd) {
          l = mid + 1;
          at = mid;
        } else {
          r = mid - 1;
        }
      }
      long long curPlus = (at - dist + 1) % M;
      curPlus = (curPlus * curGcd) % M;
      ans += curPlus;
      ans %= M;
      dist = at + 1;
    }
  }
  cout << (ans % M + M) % M << '\n';

  return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef pair<long long, long long> pll;

const int N = 1e5 + 5;
const long long M = 1e9 + 7;

int n;
vector<int> g[N];
long long x[N];
long long ans;

void dfs(int u, int p, vector<pll> vtr) {
  vector<pll> old = vtr;
  vtr.clear();
  for (auto& e : old) {
    e.first = __gcd(e.first, x[u]);
  }
  old.push_back({x[u], 1LL});
  int len = old.size();
  for (int i = 0; i < len; i++) {
    int j = i;
    long long cnt = 0;
    while (j < len && old[j].first == old[i].first) {
      cnt += old[j].second;
      j++;
    }
    vtr.push_back({old[i].first, cnt});
    i = j - 1;
  }
  old.clear();
  for (auto& e : vtr) {
    ans = (ans + e.first * e.second) % M;
  }
  for (auto v : g[u]) {
    if (v == p) continue;
    dfs(v, u, vtr);
  }
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 1, {});
  cout << ans << '\n';

  return 0;
}


#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;
const int L = ceil(log2(N)) + 3;
const long long M = 1e9 + 7;

int n;
int depth[N];
int up[N][L];
int tin[N], tout[N], tim;
vector<int> g[N];
long long ans;
long long x[N];
long long gcd[N][L];

void dfs(int u, int p, int h) {
  depth[u] = h;
  up[u][0] = p;
  gcd[u][0] = __gcd(x[u], x[p]);
  tin[u] = ++tim;
  for (int i = 1; i < L; i++) {
    up[u][i] = up[up[u][i - 1]][i - 1];
    gcd[u][i] = __gcd(gcd[u][i - 1], gcd[up[u][i - 1]][i - 1]);
  }
  for (auto v : g[u]) {
    if (v == p) continue;
    dfs(v, u, h + 1);
  }
  tout[u] = ++tim;
}

bool is_anc(int u, int v) {
  return (tin[u] <= tin[v] && tout[u] >= tout[v]);
}

int lca(int u, int v) {
  if (is_anc(u, v)) return u;
  if (is_anc(v, u)) return v;
  for (int i = L - 1; i >= 0; i--) {
    if (!is_anc(up[u][i], v)) {
      u = up[u][i];
    }
  }
  return up[u][0];
}

long long getGcd(int u, int h) {
  long long ret = x[u];
  for (int i = L - 1; i >= 0; i--) {
    if (depth[up[u][i]] >= h) {
      ret = __gcd(ret, gcd[u][i]);
      u = up[u][i];
    }
  }
  return ret;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x[i];
  }
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(1, 1, 0);
  for (int i = 1; i <= n; i++) {
    int dist = 0;
    while (dist <= depth[i]) {
      long long curGcd = getGcd(i, dist);
      int l = dist, r = depth[i], at = dist;
      while (l <= r) {
        int mid = (l + r) >> 1;
        if (getGcd(i, mid) == curGcd) {
          l = mid + 1;
          at = mid;
        } else {
          r = mid - 1;
        }
      }
      long long curPlus = (at - dist + 1) % M;
      curPlus = (curPlus * curGcd) % M;
      ans += curPlus;
      ans %= M;
      dist = at + 1;
    }
  }
  cout << (ans % M + M) % M << '\n';

  return 0;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author indy256
 */

#include <bits/stdc++.h>

using namespace std;

constexpr int mod = 1000'000'007;
long long res;

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

void dfs(const vector<vector<int>> &g, const vector<int> &x, int u, int p, map<int, int> &a) {
    map<int, int> b;
    for (auto[v, cnt] : a) {
        int vv = gcd(v, x[u]);
        res += vv * cnt % mod;
        res %= mod;
        b[vv] += cnt;
    }
    res += x[u];
    res %= mod;
    b[x[u]] += 1;
    for (int v : g[u]) {
        if (v == p)continue;
        dfs(g, x, v, u, b);
    }
}

void solve(istream &in, ostream &out) {
    int n;
    in >> n;

    vector<int> x(n);
    for (int i = 0; i < n; ++i) {
        long long v;
        in >> v;
        x[i] = v % mod;
    }

    vector<vector<int>> g(n, vector<int>());
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        in >> a >> b;
        --a;
        --b;
        g[a].emplace_back(b);
        g[b].emplace_back(a);
    }

    res = 0;
    map<int, int> m;
    dfs(g, x, 0, -1, m);
    out << res << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    std::istream& in(std::cin);
    std::ostream& out(std::cout);
    solve(in, out);
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author indy256
 */

#include <bits/stdc++.h>

using namespace std;

constexpr int mod = 1000'000'007;
long long res;

long long gcd(long long a, long long b) {
    return b == 0 ? a : gcd(b, a % b);
}

void dfs(const vector<vector<int>> &g, const vector<long long> &x, int u, int p, map<long long, int> &a) {
    map<long long, int> b;
    for (auto[v, cnt] : a) {
        long long vv = gcd(v, x[u]);
        res += vv * cnt % mod;
        res %= mod;
        b[vv] += cnt;
    }
    res += x[u];
    res %= mod;
    b[x[u]] += 1;
    for (int v : g[u]) {
        if (v == p)continue;
        dfs(g, x, v, u, b);
    }
}

void solve(istream &in, ostream &out) {
    int n;
    in >> n;

    vector<long long> x(n);
    for (int i = 0; i < n; ++i) {
        in >> x[i];
    }

    vector<vector<int>> g(n, vector<int>());
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        in >> a >> b;
        --a;
        --b;
        g[a].emplace_back(b);
        g[b].emplace_back(a);
    }

    res = 0;
    map<long long, int> m;
    dfs(g, x, 0, -1, m);
    out << res << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    std::istream& in(std::cin);
    std::ostream& out(std::cout);
    solve(in, out);
}


#include <iostream>
#include <vector>

using namespace std;

#define INIT()             \
  ios::sync_with_stdio(0); \
  cin.tie(0)

#define DBG(a) cerr << #a " = " << a << endl

typedef long long ll;

#define $T template
#define $C class

$T<$C T = int, $C S = T> T input() { T x; cin >> (S &)x; return x; }

template<class T>
T gcd(T x, T y) {
  while (y)
    y ^= x ^= y ^= x %= y;
  return x;
}

struct Node {
  ll x;
  Node *parent;
  vector<Node*> neigh;
  Node *decGcdAnc;
  int depth;
  int sumToRoot;
};

const ll M = 1000000007;

int calc(Node *n) {
  Node *anc = n->parent;

  while (anc && (n->x != 0 && anc->x % n->x == 0 || n->x == 0 && anc->x == 0)) {
    anc = anc->decGcdAnc;
  }
  n->decGcdAnc = anc;
  n->sumToRoot = 0;
  ll curX = n->x;
  int curDepth = n->depth;
  while (anc) {
    n->sumToRoot = (n->sumToRoot + curX % M * (curDepth - anc->depth)) % M;
    curDepth = anc->depth;
    curX = gcd(curX, anc->x);
    if (curX == anc->x) {
      n->sumToRoot = (n->sumToRoot + anc->sumToRoot) % M;
      break;
    }
    anc = anc->decGcdAnc;
  }
  if (!anc) {
    n->sumToRoot = (n->sumToRoot + curX % M * (curDepth + 1)) % M;
  }

  ll subtreeSumToRoot = n->sumToRoot;
  for (Node *v : n->neigh) {
    if (v != n->parent) {
      v->parent = n;
      v->depth = n->depth + 1;
      subtreeSumToRoot += calc(v);
    }
  }
  return subtreeSumToRoot % M;
}

int main() {
  INIT();

  vector<Node> nodes;
  int n;
  cin >> n;
  nodes.resize(n);
  for (Node &nd : nodes) {
    cin >> nd.x;
  }
  for (int i = 0; i < n - 1; ++i) {
    int a = input() - 1;
    int b = input() - 1;
    nodes[a].neigh.push_back(&nodes[b]);
    nodes[b].neigh.push_back(&nodes[a]);
  }
  Node *root = &nodes[0];
  root->depth = 0;
  root->parent = nullptr;
  root->decGcdAnc = nullptr;
  cout << calc(root) << endl;
  return 0;
}


#include <TTStd.h>
#include <Math/GCD.h>

#include <vector>

struct Node {
  ll x;
  Node *parent;
  vector<Node*> neigh;
  Node *decGcdAnc;
  int depth;
  int sumToRoot;
};

const ll M = 1000000007;

int calc(Node *n) {
  Node *anc = n->parent;

  while (anc && (n->x != 0 && anc->x % n->x == 0 || n->x == 0 && anc->x == 0)) {
    anc = anc->decGcdAnc;
  }
  n->decGcdAnc = anc;
  n->sumToRoot = 0;
  ll curX = n->x;
  int curDepth = n->depth;
  while (anc) {
    n->sumToRoot = (n->sumToRoot + curX % M * (curDepth - anc->depth)) % M;
    curDepth = anc->depth;
    curX = gcd(curX, anc->x);
    if (curX == anc->x) {
      n->sumToRoot = (n->sumToRoot + anc->sumToRoot) % M;
      break;
    }
    anc = anc->decGcdAnc;
  }
  if (!anc) {
    n->sumToRoot = (n->sumToRoot + curX % M * (curDepth + 1)) % M;
  }

  ll subtreeSumToRoot = n->sumToRoot;
  for (Node *v : n->neigh) {
    if (v != n->parent) {
      v->parent = n;
      v->depth = n->depth + 1;
      subtreeSumToRoot += calc(v);
    }
  }
  return subtreeSumToRoot % M;
}

int main() {
  INIT();

  vector<Node> nodes;
  int n;
  cin >> n;
  nodes.resize(n);
  for (Node &nd : nodes) {
    cin >> nd.x;
  }
  for (int i = 0; i < n - 1; ++i) {
    int a = input() - 1;
    int b = input() - 1;
    nodes[a].neigh.push_back(&nodes[b]);
    nodes[b].neigh.push_back(&nodes[a]);
  }
  Node *root = &nodes[0];
  root->depth = 0;
  root->parent = nullptr;
  root->decGcdAnc = nullptr;
  cout << calc(root) << endl;
  return 0;
}


#include <iostream>
#include <map>
#include <vector>

using namespace std;

#define INIT()             \
  ios::sync_with_stdio(0); \
  cin.tie(0)

#define DBG(a) cerr << #a " = " << a << endl

typedef long long ll;

#define $T template
#define $C class

$T<$C T = int, $C S = T> T input() { T x; cin >> (S &)x; return x; }

template<class T>
T gcd(T x, T y) {
  while (y)
    y ^= x ^= y ^= x %= y;
  return x;
}

struct Node {
  ll x;
  Node *parent;
  vector<Node*> neigh;
  vector<pair<ll,int>> gcdCount;
};

const ll M = 1000000007;

int calc(Node *n) {
  if (n->parent) {
    n->gcdCount.reserve(n->parent->gcdCount.size() + 1);
  }
  n->gcdCount.emplace_back(n->x, 1);
  if (n->parent) {
    for (auto e : n->parent->gcdCount) {
      ll g = gcd(n->x, e.first);
      if (g != n->gcdCount.back().first) {
        n->gcdCount.emplace_back(g, 0);
      }
      n->gcdCount.back().second += e.second;
    }
  }

  ll sumToRoot = 0;
  for (auto e : n->gcdCount) {
    sumToRoot += e.first * e.second;
  }

  ll subtreeSumToRoot = sumToRoot;
  for (Node *v : n->neigh) {
    if (v != n->parent) {
      v->parent = n;
      subtreeSumToRoot += calc(v);
    }
  }
  return subtreeSumToRoot % M;
}

int main() {
  INIT();

  vector<Node> nodes;
  int n;
  cin >> n;
  nodes.resize(n);
  for (Node &nd : nodes) {
    cin >> nd.x;
  }
  for (int i = 0; i < n - 1; ++i) {
    int a = input() - 1;
    int b = input() - 1;
    nodes[a].neigh.push_back(&nodes[b]);
    nodes[b].neigh.push_back(&nodes[a]);
  }
  Node *root = &nodes[0];
  root->parent = nullptr;
  cout << calc(root) << endl;
  return 0;
}


#include <iostream>
#include <map>
#include <vector>

using namespace std;

#define INIT()             \
  ios::sync_with_stdio(0); \
  cin.tie(0)

#define DBG(a) cerr << #a " = " << a << endl

typedef long long ll;

#define $T template
#define $C class

$T<$C T = int, $C S = T> T input() { T x; cin >> (S &)x; return x; }

template<class T>
T gcd(T x, T y) {
  while (y)
    y ^= x ^= y ^= x %= y;
  return x;
}

struct Node {
  ll x;
  Node *parent;
  vector<Node*> neigh;
  map<ll,int> gcdCount;
};

const ll M = 1000000007;

int calc(Node *n) {
  n->gcdCount[n->x] = 1;
  if (n->parent) {
    for (auto e : n->parent->gcdCount) {
      n->gcdCount[gcd(n->x, e.first)] += e.second;
    }
  }

  ll sumToRoot = 0;
  for (auto e : n->gcdCount) {
    sumToRoot += e.first * e.second;
  }

  ll subtreeSumToRoot = sumToRoot;
  for (Node *v : n->neigh) {
    if (v != n->parent) {
      v->parent = n;
      subtreeSumToRoot += calc(v);
    }
  }
  return subtreeSumToRoot % M;
}

int main() {
  INIT();

  vector<Node> nodes;
  int n;
  cin >> n;
  nodes.resize(n);
  for (Node &nd : nodes) {
    cin >> nd.x;
  }
  for (int i = 0; i < n - 1; ++i) {
    int a = input() - 1;
    int b = input() - 1;
    nodes[a].neigh.push_back(&nodes[b]);
    nodes[b].neigh.push_back(&nodes[a]);
  }
  Node *root = &nodes[0];
  root->parent = nullptr;
  cout << calc(root) << endl;
  return 0;
}


#include <iostream>
#include <vector>

using namespace std;

#define INIT()             \
  ios::sync_with_stdio(0); \
  cin.tie(0)

#define DBG(a) cerr << #a " = " << a << endl

typedef long long ll;

#define $T template
#define $C class

$T<$C T = int, $C S = T> T input() { T x; cin >> (S &)x; return x; }

template<class T>
T gcd(T x, T y) {
  while (y)
    y ^= x ^= y ^= x %= y;
  return x;
}

struct Node {
  ll x;
  Node *parent;
  vector<Node*> neigh;
  Node *decGcdAnc;
  int depth;
};

const ll M = 1000000007;

int calc(Node *n) {
  Node *anc = n->parent;

  while (anc && (n->x != 0 && anc->x % n->x == 0 || n->x == 0 && anc->x == 0)) {
    anc = anc->decGcdAnc;
  }
  n->decGcdAnc = anc;
  int sumToRoot = 0;
  ll curX = n->x;
  int curDepth = n->depth;
  while (anc) {
    sumToRoot = (sumToRoot + curX % M * (curDepth - anc->depth)) % M;
    curDepth = anc->depth;
    curX = gcd(curX, anc->x);
    anc = anc->decGcdAnc;
  }
  sumToRoot = (sumToRoot + curX % M * (curDepth + 1)) % M;

  ll subtreeSumToRoot = sumToRoot;
  for (Node *v : n->neigh) {
    if (v != n->parent) {
      v->parent = n;
      v->depth = n->depth + 1;
      subtreeSumToRoot += calc(v);
    }
  }
  return subtreeSumToRoot % M;
}

int main() {
  INIT();

  vector<Node> nodes;
  int n;
  cin >> n;
  nodes.resize(n);
  for (Node &nd : nodes) {
    cin >> nd.x;
  }
  for (int i = 0; i < n - 1; ++i) {
    int a = input() - 1;
    int b = input() - 1;
    nodes[a].neigh.push_back(&nodes[b]);
    nodes[b].neigh.push_back(&nodes[a]);
  }
  Node *root = &nodes[0];
  root->depth = 0;
  root->parent = nullptr;
  root->decGcdAnc = nullptr;
  cout << calc(root) << endl;
  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
ll ans[MAXN];

gp_hash_table<ll, int> *dfs(int u, int p)
{
  gp_hash_table<ll, int> *table = new gp_hash_table<ll, int>;
  sum = (sum + a[u]) % MOD;
  ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    auto res = dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && p != -1) || (p == -1 && g[u].size() == 1)))
    {
      table = res;
      sum = (sum + ans[v]) % MOD;
      ans[u] = (ans[u] + ans[v]) % MOD;
    }
    else
    {
      for (auto i : *res)
      {
        ll gcd = __gcd(a[u], i.first);
        (*table)[gcd] += i.second;
        sum = (sum + gcd * i.second) % MOD;
        ans[u] = (a[u] + gcd * i.second) % MOD;
      }
    }
  }
 (*table)[a[u]]++;
  return table;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int L = 16;
const int MOD = (int)1e9 + 7;

ll ans;
ll a[MAXN];
ll dp[L][MAXN];
int p[L][MAXN];
int h[MAXN];
vector <int> g[MAXN];

void dfs(int u)
{
  if (u == 1)
    p[0][u] = u;
  dp[0][u] = a[p[0][u]];

  for (int l = 1; l < L; l++)
  {
    p[l][u] = p[l - 1][p[l - 1][u]];
    dp[l][u] = __gcd(dp[l - 1][u], dp[l - 1][p[l - 1][u]]);
  }

  int cur = u, prv = u;
  ll curv = a[u];
  while (1)
  {
    for (int l = L - 1; l >= 0; l--)
    {
      if (__gcd(curv, dp[l][cur]) == curv)
      {
        cur = p[l][cur];
      }
    }
    ans = (ans + (h[prv] - h[cur] + 1) * curv) % MOD;
    if (cur == 1)
      break;
    prv = p[0][cur];
    curv = __gcd(curv, dp[0][cur]);
    cur = p[0][cur];
  }

  for (int v : g[u])
  {
    if (v == p[0][u])
      continue;
    h[v] = h[u] + 1;
    p[0][v] = u;
    dfs(v);
  }
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1);
  cout << ans;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
ll ans[MAXN];

gp_hash_table<ll, int> tbl[MAXN];
int pt = 0;

int dfs(int u, int p)
{
  int table = pt++;
  ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    auto res = dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && u != 1) || (u == 1 && g[u].size() == 1)))
    {
      table = res;
      ans[u] = (ans[u] + ans[v]) % MOD;
    }
    else
    {
      for (auto &i : tbl[table])
      {
        ll gcd = __gcd(a[u], i.first);
        tbl[table][gcd] += i.second;
        ans[u] = (ans[u] + gcd * i.second) % MOD;
      }
    }
  }
  tbl[table][a[u]]++;
  sum = (sum + ans[u]) % MOD;
  return table;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];

gp_hash_table<ll, int> dfs(int u, int p)
{
  gp_hash_table<ll, int> table;
  table[a[u]] = 1;
  sum += a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    auto res = dfs(v, u);
    for (auto i : res)
    {
      ll gcd = __gcd(a[u], i.first);
      table[gcd] += i.second;
      sum = (sum + gcd * i.second) % MOD;
    }
  }
  return table;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
ll ans[MAXN];

gp_hash_table<ll, int> tbl[MAXN];
int pt = 0;

bool clrd[MAXN];
int table[MAXN];

void clear(int u)
{
  clrd[u] = 1;
  tbl[table[u]].clear();
  for (int v : g[u])
    if (!clrd[u])
      clear(v);
}

void dfs(int u, int p)
{
  table[u] = pt++;
  ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && u != 1) || (u == 1 && g[u].size() == 1)))
    {
      table[u] = table[v];
      ans[u] = (ans[u] + ans[v]) % MOD;
    }
    else
    {
      for (auto i : tbl[table[v]])
      {
        ll gcd = __gcd(a[u], i.first);
        tbl[table[u]][gcd] += i.second;
        ans[u] = (ans[u] + gcd * i.second) % MOD;
      }
      clear(v);
    }
  }
  tbl[table[u]][a[u]]++;
  sum = (sum + ans[u]) % MOD;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
ll ans[MAXN];

gp_hash_table<ll, int> tbl[MAXN];
int pt = 0;

int dfs(int u, int p)
{
  int table = pt++;
  ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    auto res = dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && u != 1) || (u == 1 && g[u].size() == 1)))
    {
      table = res;
      ans[u] = (ans[u] + ans[v]) % MOD;
    }
    else
    {
      for (auto i : tbl[res])
      {
        ll gcd = __gcd(a[u], i.first);
        tbl[table][gcd] += i.second;
        ans[u] = (ans[u] + gcd * i.second) % MOD;
      }
    }
  }
  tbl[table][a[u]]++;
  sum = (sum + ans[u]) % MOD;
  return table;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
int ans[MAXN];

gp_hash_table<ll, int> *dfs(int u, int p)
{
  gp_hash_table<ll, int> *table = new gp_hash_table<ll, int>;
  sum = (sum + a[u]) % MOD;
 ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    auto res = dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && p != -1) || (p == -1 && g[u].size() == 1)))
    {
      table = res;
      sum = (sum + ans[v]) % MOD;
    }
    else
    {
      for (auto i : *res)
      {
        ll gcd = __gcd(a[u], i.first);
        (*table)[gcd] += i.second;
        sum = (sum + gcd * i.second) % MOD;
        ans[u] = (a[u] + (ll)gcd * i.second) % MOD;
      }
    }
  }
 (*table)[a[u]]++;
  return table;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


/*
  I_🧡🧡🧡_QMsh
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using namespace __gnu_pbds; // gp_hash_table<int, int> table;

template <typename T> void smin(T &a, const T &b) { a = (a < b ? a : b); }
template <typename T> void smax(T &a, const T &b) { a = (a > b ? a : b); }

typedef long long ll;
typedef long double ld;

const int MAXN = 1e5 + 30;
const int MOD = (int)1e9 + 7;

ll sum = 0;
vector <int> g[MAXN];
ll a[MAXN];
ll ans[MAXN];

gp_hash_table<ll, int> tbl[MAXN];
int pt = 0;

bool clrd[MAXN];
int table[MAXN];

void clear(int u, int p)
{
  clrd[u] = 1;
  tbl[table[u]].clear();
  for (int v : g[u])
  if (!clrd[v] && v != p)
    clear(v, u);
}

void dfs(int u, int p)
{
  table[u] = pt++;
  ans[u] = a[u];
  for (int v : g[u])
  {
    if (v == p)
      continue;
    dfs(v, u);
    if (__gcd(a[u], a[v]) == a[v] && ((g[u].size() == 2 && u != 1) || (u == 1 && g[u].size() == 1)))
    {
      table[u] = table[v];
      ans[u] = (ans[u] + ans[v]) % MOD;
    }
    else
    {
      for (auto i : tbl[table[v]])
      {
        ll gcd = __gcd(a[u], i.first);
        tbl[table[u]][gcd] += i.second;
        ans[u] = (ans[u] + gcd * i.second) % MOD;
      }
      clear(v, u);
    }
  }
  tbl[table[u]][a[u]]++;
  sum = (sum + ans[u]) % MOD;
}

signed main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  for (int i = 1; i < n; i++)
  {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1, -1);
  cout << sum;

  return 0;
}


import sys,threading
sys.setrecursionlimit(2*(10**5))
def dfs(index,d,visited,p,dep,ans):
    visited[index]=True
    dep[index]=d
    for i in range(len(ans[index])):
        if (visited[ans[index][i]]==False):
            dfs(ans[index][i],d+1,visited,p,dep,ans)
            p[index]+=p[ans[index][i]]

def solve():
       n=list(map(int,input().split()))
       arr=list(map(int,input().split()))
       n=int(n[0])
       ma=0
       i=0
       sum=0
       while(i<n):
           ma=0
           while(i<n and arr[i]>0):
               ma=max(arr[i],ma)
               i+=1
           sum+=ma
           mi=0
           c=0
           while(i<n and arr[i]<0):
               if (c==0):
                   mi=arr[i]
               mi=max(arr[i],mi)
               c=1
               i+=1
           if (c==1):
               sum+=mi
       print(sum)

def main():
    t=input().split()
    t=int(t[0])
    for _ in range(t):
       solve()

if __name__=="__main__":
    sys.setrecursionlimit(2**32//2-1)
    threading.stack_size(1 << 27)
    thread = threading.Thread(target=main)
    thread.start()
    thread.join()


import sys,threading
sys.setrecursionlimit(2*(10**5))
def dfs(index,d,visited,p,dep,ans):
    visited[index]=True
    dep[index]=d
    for i in range(len(ans[index])):
        if (visited[ans[index][i]]==False):
            dfs(ans[index][i],d+1,visited,p,dep,ans)
            p[index]+=p[ans[index][i]]

def solve():
       n=list(map(int,input().split()))
       arr=list(map(int,input().split()))
       n=int(n[0])
       k=int(n/2)
       sum=0
       max=0
       sign=1
       i=0
       m=0
       c=0
       l=0
       max_l=0
       while(i<len(arr)):
           #print("i==",i,'  ',sum)
           if (i==0):
               if (arr[i]<0):
                   sign=-1
               else:
                   sign=1
           if (sign*arr[i]>0):
               sum+=arr[i]
               c=1
               l+=1
               sign=sign*(-1)
           else:
               if (c==0):
                   sum+=arr[i]
               c=0
               if (m==0):
                   max=sum
                   m=1
               if (max<=sum and max_l<=l):
                   max=sum
                   max_l=l
                   l=0
               if (arr[i]<0):
                   sign=-1
               else:
                   sign=1
               sum=0
               i-=1
           i+=1
       if ((max<sum or m==0) and (max_l<=l)):
           max=sum
       print(max)

def main():
    t=input().split()
    t=int(t[0])
    for _ in range(t):
       solve()

if __name__=="__main__":
    sys.setrecursionlimit(2**32//2-1)
    threading.stack_size(1 << 27)
    thread = threading.Thread(target=main)
    thread.start()
    thread.join()


case = int(input())
for n in range(case):
	n = int(input())
	a = list(map(lambda x : int(x), input().split()))
	goal = []
	left = 0
	right = 0
	for i in range(len(a)):
		if (i == 0):
			left = 0
			continue
		if (a[i]*a[i-1] < 0):
			right = i
			sliced = a[left:right]
			goal.append(max(sliced))
			left = i
			continue
	right = n-1
	if (left == right): goal.append(a[n-1])
	else:
		sliced = a[left:right]
		goal.append(max(sliced))
	s = sum(goal)
	print(s)


case = int(input())
for n in range(case):
	n = int(input())
	a = list(map(lambda x : int(x), input().split()))
	goal = []
	left = 0
	right = 0
	for i in range(len(a)):
		if (i == 0):
			left = 0
			continue
		if (a[i]*a[i-1] < 0):
			right = i
			sliced = a[left:right]
			goal.append(max(sliced))
			left = i
			continue
	right = n-1
	if (left == right): goal.append(a[n-1])
	else:
		sliced = a[left:right+1]
		print("s",sliced)
		goal.append(max(sliced))
	s = sum(goal)
	print(s)


case = int(input())
for n in range(case):
	n = int(input())
	a = list(map(lambda x : int(x), input().split()))
	goal = []
	s = 0
	goal.append(a[0])
	for i in range(1,n):
		if a[i] * a[i-1] < 0:
			s = s + max(goal)
			goal = []
		goal.append(a[i])
	s = s + max(goal)
	print(s)


for _ in range(int(input())):

    n=int(input())
    l=list(map(int,input().split()))
    t1=[]
    t2=set()

    j=[]

    for i in range(1,n):
#        print(l[i],l[i-1])
        if l[i]>0 and l[i-1]<0:
            if len(j)>0:
                j.append(l[i])

            else:
                j.append(l[i])
                j.append(l[i-1])

        elif l[i]<0 and l[i-1]>0:
            if len(j)>0:
                j.append(l[i])

            else:
                j.append(l[i])
                j.append(l[i-1])

        else:
            if len(j)>1:
                t1.append(j)
            else:
                t2.add(l[i-1])
                t2.add(l[i])

            j=[]

    t1.append(j)
    mxx=-pow(10,18)

    if len(t1)>0 and len(t1[0])>0:

        for i in range(len(t1)):

            t1[i]=list(t1[i])
            k=sum(t1[i])

            if k>mxx:
                mxx=k

    else:
        t2=list(t2)
        for i in range(len(t2)):
            if t2[i]>mxx:
                mxx=t2[i]

    print(mxx)


for _ in range(int(input())):

    n=int(input())
    l=list(map(int,input().split()))
    t1=[]
    t2=set()

    j=[]
    if n==1:
        t2.add(l[0])

    else:

        for i in range(1,n):
#        print(l[i],l[i-1])
            if l[i]>0 and l[i-1]<0:
                if len(j)>0:
                    j.append(l[i])

                else:
                    j.append(l[i])
                    j.append(l[i-1])

            elif l[i]<0 and l[i-1]>0:
                if len(j)>0:
                    j.append(l[i])

                else:
                    j.append(l[i])
                    j.append(l[i-1])

            else:
                if len(j)>1:
                    t1.append(j)
                else:
                    t2.add(l[i-1])
                    t2.add(l[i])

                j=[]

        t1.append(j)
    mxx=-pow(10,18)

    if len(t1)>0 and len(t1[0])>0:

        for i in range(len(t1)):

            t1[i]=list(t1[i])
            k=sum(t1[i])

            if k>mxx:
                mxx=k

    else:
        t2=list(t2)
        for i in range(len(t2)):
            if t2[i]>mxx:
                mxx=t2[i]

    print(mxx)


for _ in range(int(input())):

    n=int(input())

    l=list(map(int,input().split()))

    su=i=mxx=0

    while i<=n-1:
        mxx=-pow(10,18)
        if l[i]>0:

            j=i
            while j<n and l[j] > 0 :
                if mxx<l[j]:
                    mxx=l[j]
                j+=1

            su+=mxx
            i=j

        else:
            j=i
            while(j<n and l[j]<0):
                if mxx<l[j]:
                    mxx=l[j]
                j+=1

            su+=mxx
            i=j

    print(su)


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase
import datetime

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    for _ in range(int(input())):
        n=int(input())
        a=[int(x) for x in input().split()]
        a.append(a[n-1]*-1)
        k=0
        maxp=1
        maxn=-9999999999999999999
        ts=0
        pos=0
        neg=0
        for i in range(n):
            if a[i]<0:
                neg+=1
                maxn=max(maxn,a[i])
                if a[i+1]>0:
                    ts+=(maxn)
                    maxn=-9999999999999999999

            if a[i]>0:
                pos+=1
                maxp=max(maxp,a[i])
                if a[i+1]<0:
                    ts+=(maxp)
                    maxp=1

        print(ts)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase
import datetime

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    starttime=datetime.datetime.now()
    #ifndef ONLINE_JUDGE
    # sys.stdin=open('input.txt','r')
    # sys.stdout=open('output.txt','w')
    #endif
    for _ in range(int(input())):
        n=int(input())
        a=[int(x) for x in input().split()]
        a.append(a[n-1]*-1)
        k=0
        maxp=1
        maxn=-9999999999999999999
        ts=0
        pos=0
        neg=0
        for i in range(n):
            if a[i]<0:
                neg+=1
                maxn=max(maxn,a[i])
                if a[i+1]>0:
                    ts+=(maxn)
                    maxn=-9999999999999999999

            if a[i]>0:
                pos+=1
                maxp=max(maxp,a[i])
                if a[i+1]<0:
                    ts+=(maxp)
                    maxp=1

        print(ts)

    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    # print("Time:",time,"ms")

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math
from collections import deque
import collections

def main():
    for _ in range(int(input())):
        n=ri()
        a=ria()
        a.append(a[n-1]*-1)
        k=0
        maxp=1
        maxn=-9999999999999999999
        ts=0
        pos=0
        neg=0
        for i in range(n):
            if a[i]<0:
                neg+=1
                maxn=max(maxn,a[i])
                if a[i+1]>0:
                    ts+=(maxn)
                    maxn=-9999999999999999999

            if a[i]>0:
                pos+=1
                maxp=max(maxp,a[i])
                if a[i+1]<0:
                    ts+=(maxp)
                    maxp=1

        wi(ts)

class FastReader(io.IOBase):
    newlines = 0

    def __init__(self, fd, chunk_size=1024 * 8):
        self._fd = fd
        self._chunk_size = chunk_size
        self.buffer = io.BytesIO()

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self, size=-1):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

class FastWriter(io.IOBase):

    def __init__(self, fd):
        self._fd = fd
        self.buffer = io.BytesIO()
        self.write = self.buffer.write

    def flush(self):
        os.write(self._fd, self.buffer.getvalue())
        self.buffer.truncate(0), self.buffer.seek(0)

class FastStdin(io.IOBase):
    def __init__(self, fd=0):
        self.buffer = FastReader(fd)
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

class FastStdout(io.IOBase):
    def __init__(self, fd=1):
        self.buffer = FastWriter(fd)
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.flush = self.buffer.flush

if __name__ == '__main__':
    sys.stdin = FastStdin()
    sys.stdout = FastStdout()
    main()


def seg(L):
    i = 1
    j = 0
    segset = []
    while i < len(L):
        try:
            while L[i]*L[i-1] > 0:
                i += 1
        except IndexError:
            pass
        segset.append(L[j:i])
        j = i
        i += 1
    if L[-2]*L[-1] < 0:
        segset.append([L[-1]])
    return segset

for _ in range(int(input())):
    n = int(input())
    A = list(map(int, input().split()))
    print(sum([max(elem) for elem in seg(A)]))


def seg(L):
    if all(x<0 for x in L) or all(x>0 for x in L):
        return [L]
    else:
        i = 1
        j = 0
        segset = []
        while i < len(L):
            try:
                while L[i]*L[i-1] > 0:
                    i += 1
            except IndexError:
                pass
            segset.append(L[j:i])
            j = i
            i += 1
        if L[-2]*L[-1] < 0:
            segset.append([L[-1]])
        return segset

for _ in range(int(input())):
    n = int(input())
    A = list(map(int, input().split()))
    print(sum([max(elem) for elem in seg(A)]))


number = int(input())

for k in range(number):
    length = int(input())
    sequence=[]
    for l in range(length):
        new = int(input())
        sequence.append(new)

    subsequence_length = 1
    toggle=0
    toggled=0
    total=0
    currentmax=0

    if sequence[0]>0:
        toggle = 1
    else:
        toggle = -1
    #print('Set initial toggle to',toggle)

    #print('Testing sequence',sequence)

    for i in range(len(sequence)):
        if sequence[i]>0 and toggle==-1:
            #print('Toggled!',sequence[i],'is positive')
            subsequence_length += 1
            toggle = 1
            toggled = 1
        elif sequence[i]<0 and toggle==1:
            #print('Toggled!', sequence[i], 'is negative')
            subsequence_length += 1
            toggle = -1
            toggled = 1
        if toggled==1:
            total = total+currentmax
            #print('New total is', total)
            currentmax=0
            toggled = 0
            currentmax=sequence[i]
        if i==len(sequence)-1:
            total = total+currentmax
        else:
            if sequence[i]>currentmax or currentmax==0:
                currentmax = sequence[i]

    #(subsequence_length)
    print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    if len(sequence)==1:
        print(sequence[0])
    else:
        subsequence_length = 1
        toggle=0
        toggled=0
        total=0
        currentmax=0

        if sequence[0]>0:
            toggle = 1
        else:
            toggle = -1
        #print('Set initial toggle to',toggle)

        #print('Testing sequence',sequence)

        for i in range(len(sequence)):
            if sequence[i]>0 and toggle==-1:
                #print('Toggled!',sequence[i],'is positive')
                subsequence_length += 1
                toggle = 1
                toggled = 1
            elif sequence[i]<0 and toggle==1:
                #print('Toggled!', sequence[i], 'is negative')
                subsequence_length += 1
                toggle = -1
                toggled = 1
            if toggled==1:
                total = total+currentmax
                #print('New total is', total)
                currentmax=0
                toggled = 0
                currentmax=sequence[i]
            if sequence[i]>currentmax or currentmax==0 or total==0:
                    currentmax = sequence[i]
                    #print('New block max is',currentmax)
            if i==len(sequence)-1:
                total = total+currentmax

        #(subsequence_length)
        print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    if len(sequence)==1:
        print(sequence[0])
    else:
        subsequence_length = 1
        toggle=0
        toggled=0
        total=0
        currentmax=0

        if sequence[0]>0:
            toggle = 1
        else:
            toggle = -1
        #print('Set initial toggle to',toggle)

        #print('Testing sequence',sequence)

        for i in range(len(sequence)):
            if sequence[i]>0 and toggle==-1:
                #print('Toggled!',sequence[i],'is positive')
                subsequence_length += 1
                toggle = 1
                toggled = 1
            elif sequence[i]<0 and toggle==1:
                #print('Toggled!', sequence[i], 'is negative')
                subsequence_length += 1
                toggle = -1
                toggled = 1
            if toggled==1:
                total = total+currentmax
                #print('New total is', total)
                currentmax=0
                toggled = 0
                currentmax=sequence[i]
            if i==len(sequence)-1:
                total = total+currentmax
            else:
                if sequence[i]>currentmax or currentmax==0 or total==0:
                    currentmax = sequence[i]

        #(subsequence_length)
        print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    subsequence_length = 1
    toggle=0
    toggled=0
    total=0
    currentmax=0

    if sequence[0]>0:
        toggle = 1
    else:
        toggle = -1
    #print('Set initial toggle to',toggle)

    #print('Testing sequence',sequence)

    for i in range(len(sequence)):
        if sequence[i]>0 and toggle==-1:
            #print('Toggled!',sequence[i],'is positive')
            subsequence_length += 1
            toggle = 1
            toggled = 1
        elif sequence[i]<0 and toggle==1:
            #print('Toggled!', sequence[i], 'is negative')
            subsequence_length += 1
            toggle = -1
            toggled = 1
        if toggled==1:
            total = total+currentmax
            #print('New total is', total)
            currentmax=0
            toggled = 0
            currentmax=sequence[i]
        if i==len(sequence)-1:
            total = total+currentmax
        else:
            if sequence[i]>currentmax or currentmax==0:
                currentmax = sequence[i]

    #(subsequence_length)
    print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    if len(sequence))==1:
        print(sequence[0])
    else:
        subsequence_length = 1
        toggle=0
        toggled=0
        total=0
        currentmax=0

        if sequence[0]>0:
            toggle = 1
        else:
            toggle = -1
        #print('Set initial toggle to',toggle)

        #print('Testing sequence',sequence)

        for i in range(len(sequence)):
            if sequence[i]>0 and toggle==-1:
                #print('Toggled!',sequence[i],'is positive')
                subsequence_length += 1
                toggle = 1
                toggled = 1
            elif sequence[i]<0 and toggle==1:
                #print('Toggled!', sequence[i], 'is negative')
                subsequence_length += 1
                toggle = -1
                toggled = 1
            if toggled==1:
                total = total+currentmax
                #print('New total is', total)
                currentmax=0
                toggled = 0
                currentmax=sequence[i]
            if i==len(sequence)-1:
                total = total+currentmax
            else:
                if sequence[i]>currentmax or currentmax==0:
                    currentmax = sequence[i]

        #(subsequence_length)
        print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    if len(sequence)==1:
        print(sequence[0])
    else:
        subsequence_length = 1
        toggle=0
        toggled=0
        total=0
        currentmax=0

        if sequence[0]>0:
            toggle = 1
        else:
            toggle = -1
        #print('Set initial toggle to',toggle)

        #print('Testing sequence',sequence)

        for i in range(len(sequence)):
            if sequence[i]>0 and toggle==-1:
                #print('Toggled!',sequence[i],'is positive')
                subsequence_length += 1
                toggle = 1
                toggled = 1
            elif sequence[i]<0 and toggle==1:
                #print('Toggled!', sequence[i], 'is negative')
                subsequence_length += 1
                toggle = -1
                toggled = 1
            if toggled==1:
                total = total+currentmax
                #print('New total is', total)
                currentmax=0
                toggled = 0
                currentmax=sequence[i]
            if i==len(sequence)-1:
                total = total+currentmax
            else:
                if sequence[i]>currentmax or currentmax==0:
                    currentmax = sequence[i]

        #(subsequence_length)
        print(total)


number = int(input())

for k in range(number):
    length = int(input())
    text_sequence=input()
    sequence = text_sequence.split()
    for i in range(len(sequence)):
        sequence[i]=int(sequence[i])
    #print(sequence)
    #for l in range(length):
      #  new = int(input())
       # sequence.append(new)

    if len(sequence)==1:
        print(sequence[0])
    else:
        subsequence_length = 1
        toggle=0
        toggled=0
        total=0
        currentmax=0

        if sequence[0]>0:
            toggle = 1
        else:
            toggle = -1
        #print('Set initial toggle to',toggle)

        #print('Testing sequence',sequence)

        for i in range(len(sequence)):
            if sequence[i]>0 and toggle==-1:
                #print('Toggled!',sequence[i],'is positive')
                subsequence_length += 1
                toggle = 1
                toggled = 1
            elif sequence[i]<0 and toggle==1:
                #print('Toggled!', sequence[i], 'is negative')
                subsequence_length += 1
                toggle = -1
                toggled = 1
            if toggled==1:
                total = total+currentmax
                #print('New total is', total)
                currentmax=0
                toggled = 0
                currentmax=sequence[i]
            if sequence[i]>currentmax or currentmax==0:
                    currentmax = sequence[i]
                    #print('New block max is',currentmax)
            if i==len(sequence)-1:
                total = total+currentmax

        #(subsequence_length)
        print(total)


for i in range(int(input())):
    n = int(input())
    a = [int(i) for i in input().split()]

    if a[0] > 0:
        ch = 1
        ma = a[0]
    else:
        ch = -1
        mi = a[0]
    sy = 0

    for j in range(1,n):
        if a[j] > 0:
            if ch == 1:
                ma = max(a[j],ma)
            else:
                sy += mi
                ch = 1
                ma = a[j]

        else:
            if ch == -1:
                ma = max(a[j],ma)
            else:
                sy += ma
                ch = -1
                mi = a[j]
    if a[-1] > 0:

        print(sy + ma)
    else:
        print(sy + mi)


for i in range(int(input())):
    n = int(input())
    a = [int(i) for i in input().split()]

    if a[0] > 0:
        ch = 1
        ma = a[0]
    else:
        ch = -1
        mi = a[0]
    sy = 0

    for j in range(1,n):
        if a[j] > 0:
            if ch == 1:
                ma = max(a[j],ma)
            else:
                sy += mi
                print(mi,1)
                ch = 1
                ma = a[j]

        else:
            if ch == -1:
                mi = max(a[j],mi)
            else:
                sy += ma

                ch = -1
                mi = a[j]
    if a[-1] > 0:

        print(sy + ma)
    else:
        print(sy + mi)


for i in range(int(input())):
    n = int(input())
    a = [int(i) for i in input().split()]

    if a[0] > 0:
        ch = 1
        ma = a[0]
    else:
        ch = -1
        mi = a[0]
    sy = 0

    for j in range(1,n):
        if a[j] > 0:
            if ch == 1:
                ma = max(a[j],ma)
            else:
                sy += mi

                ch = 1
                ma = a[j]

        else:
            if ch == -1:
                mi = max(a[j],mi)
            else:
                sy += ma

                ch = -1
                mi = a[j]
    if a[-1] > 0:

        print(sy + ma)
    else:
        print(sy + mi)


for test in range(int(input())):
    sequence_length = input()
    sequence = [int(i) for i in input().split(" ")]

    #check if there is only 1 element in the list
    if len(sequence) == 1:
        print(sequence[0])
        continue

    #sign the initial value to previous_value
    if sequence[0] > 0:
        previous_value = 'positive'
    else:
        previous_value = 'negative'

    #setting the required variables

    current_length = 1
    max_length_so_far = 1
    current_sum = sequence[0]
    max_sum_so_far = sequence[0]

    #start the program
    for number in sequence[1:]:
        #check current number is negative or positive
        if number > 0 :
            current_value = 'positive'
        else:
            current_value = 'negative'

        #now we can check if it is consecutive

        if previous_value == current_value:
            #then its not consecutive
            current_length = 1
            current_sum = number
            #don't need to assign previous_value again since they are the same

        else:
            #means that its consecutive
            previous_value = current_value

            current_length += 1
            current_sum += number

            #check if pass max_length_so_far(max sum only triggers if max length change)
            if current_length > max_length_so_far:
                max_sum_so_far = current_sum

            elif current_length == max_length_so_far:
                max_sum_so_far = max(max_sum_so_far,current_sum)

            else:
                pass

    print(max_sum_so_far)


for test in range(int(input())):
    sequence_length = input()
    sequence = [int(i) for i in input().split(" ")]

    #check if there is only 1 element in the list
    if len(sequence) == 1:
        print(sequence[0])
        continue

    #sign the initial value to previous_value
    if sequence[0] > 0:
        previous_value = 'positive'
    else:
        previous_value = 'negative'

    #setting the required variables

    current_length = 1
    max_length_so_far = 1
    current_sum = sequence[0]
    max_sum_so_far = sequence[0]

    #start the program
    for number in sequence[1:]:
        #check current number is negative or positive
        if number > 0 :
            current_value = 'positive'
        else:
            current_value = 'negative'

        #now we can check if it is consecutive
        if previous_value == current_value:
            #then its not consecutive
            current_length = 1
            current_sum = number
            #don't need to assign previous_value again since they are the same

            # print('current_sum:',current_sum,'\n','current_length:',current_length)
            #also have to check if max_sum_so_far change
            if current_length == max_length_so_far:
                max_sum_so_far = max(max_sum_so_far,current_sum)

        else:
            #means that its consecutive
            previous_value = current_value

            current_length += 1
            current_sum += number
            #print('current_length:',current_length,'max_length_so_far',max_length_so_far)
            #check if pass max_length_so_far(max sum only triggers if max length change)
            if current_length > max_length_so_far:
                max_length_so_far = current_length
                max_sum_so_far = current_sum

            elif current_length == max_length_so_far:
                max_sum_so_far = max(max_sum_so_far,current_sum)

            else:
                pass

    print(max_sum_so_far)

# i think i'm right , but the test says i'm wrong
# the test is 10 numbers:
#-2 8 3 8 -4 -15 5 -2 -3 1
# the answer they give is 6 , whitch means that they think the maximum length consecutive subarray is by length 2 digits
# but if you check it with my program , you can actually see that "-15 , 5 , -2" is a 3 digits consecutive subarray
# so the answer should be -12


# for test in range(int(input())):
#     sequence_length = input()
#     sequence = [int(i) for i in input().split(" ")]

#     #check if there is only 1 element in the list
#     if len(sequence) == 1:
#         print(sequence[0])
#         continue

#     #sign the initial value to previous_value
#     if sequence[0] > 0:
#         previous_value = 'positive'
#     else:
#         previous_value = 'negative'

#     #setting the required variables

#     current_length = 1
#     max_length_so_far = 1
#     current_sum = sequence[0]
#     max_sum_so_far = sequence[0]

#     #start the program
#     for number in sequence[1:]:
#         #check current number is negative or positive
#         if number > 0 :
#             current_value = 'positive'
#         else:
#             current_value = 'negative'

#         #now we can check if it is consecutive
#         if previous_value == current_value:
#             #then its not consecutive
#             current_length = 1
#             current_sum = number
#             #don't need to assign previous_value again since they are the same

#             #also have to check if max_sum_so_far change
#             if current_length == max_length_so_far:
#                 max_sum_so_far = max(max_sum_so_far,current_sum)

#         else:
#             #means that its consecutive
#             previous_value = current_value

#             current_length += 1
#             current_sum += number
#             #check if pass max_length_so_far(max sum only triggers if max length change)
#             if current_length > max_length_so_far:
#                 max_length_so_far = current_length
#                 max_sum_so_far = current_sum

#             elif current_length == max_length_so_far:
#                 max_sum_so_far = max(max_sum_so_far,current_sum)

#             else:
#                 pass

#     print(max_sum_so_far)

# i think i'm right , but the test says i'm wrong
# the test is 10 numbers:
#-2 8 3 8 -4 -15 5 -2 -3 1
# the answer they give is 6 , whitch means that they think the maximum length consecutive subarray is by length 2 digits
# but if you check it with my program , you can actually see that "-15 , 5 , -2" is a 3 digits consecutive subarray
# so the answer should be -12

#=======================================================================================================================
# so ..... I misunderstand the question
# the question is not to first find the maximum length subarry and print out the max_sum of the maximum length subarray...
# the question is to ask you to
# first , see the entire list as an (positive-negative-positive... or negative-positive-negative...) sequence
# which means that if you encounter a positive-positive...situation (or a negative-negative... situation , you know what i mean)
# you can pick 1 number out of all the positive-postive.. part to represtent the whole positive-positive... part
# for example -2 8 3 8 -4 -15 5 -2 -3 1
#  we see this list as a sequence of negative-positive-negative-positive-negative-positive .
# so first we only have -2 to pick , then we can pick 8 or 3 or 8 for the second part(positive) , then we can pick -4 or -15 for the thrid part ... so on
# and the goal is to maximum the sum of that sequence.
# # so finally we chose -2 , 8 , -4 , 5 , -2 , 1 . and the sum of that sequence is 6.

# for test in range(int(input())):
#     sequence_length = int(input())
#     sequence = [int(i) for i in input().split(" ")]

#     if len(sequence) == 1:
#         print(sequence[0])
#         continue

#     previous_value = 'NULL'
#     current_max_number = 'NULL'

#     end_index = sequence_length - 1
#     current_index = 0

#     answer_list = list()

#     for number in sequence:

#         if number > 0:
#             current_value = 'positive'
#         else:
#             current_value = 'negative'

#         if previous_value == 'NULL':

#             previous_value = current_value
#             current_max_number = number
#         else:
#             if current_index == end_index:
#                 if previous_value == current_value:
#                     current_max_number = max(current_max_number,number)
#                     answer_list.append(current_max_number)
#                 else:
#                     answer_list.append(current_max_number)
#                     answer_list.append(number)
#             elif previous_value == current_value:
#                 current_max_number = max(current_max_number,number)
#             else:
#                 answer_list.append(current_max_number)
#                 current_max_number=number
#                 previous_value = current_value

#         current_index += 1

#     answer = sum(answer_list)
#     print(answer)

#=========================================================================================================
#above is the right answer , but now that i think of it , i think i don't really need to create a new list
#=========================================================================================================

for test in range(int(input())):
    sequence_length = int(input())
    sequence = [int(i) for i in input().split(" ")]

    if len(sequence) == 1:
        print(sequence[0])
        continue

    previous_value = 'NULL'
    current_max_number = 'NULL'

    end_index = sequence_length - 1
    current_index = 0

    # answer_list = list()
    answer = 0

    for number in sequence:

        if number > 0:
            current_value = 'positive'
        else:
            current_value = 'negative'

        if previous_value == 'NULL':

            previous_value = current_value
            current_max_number = number
        else:
            if current_index == end_index:
                if previous_value == current_value:
                    current_max_number = max(current_max_number,number)
                    answer += current_max_number
                else:
                    answer += current_max_number
                    answer += number
            elif previous_value == current_value:
                current_max_number = max(current_max_number,number)
            else:
                answer += current_max_number
                current_max_number=number
                previous_value = current_value

        current_index += 1

    print(answer)


# for test in range(int(input())):
#     sequence_length = input()
#     sequence = [int(i) for i in input().split(" ")]

#     #check if there is only 1 element in the list
#     if len(sequence) == 1:
#         print(sequence[0])
#         continue

#     #sign the initial value to previous_value
#     if sequence[0] > 0:
#         previous_value = 'positive'
#     else:
#         previous_value = 'negative'

#     #setting the required variables

#     current_length = 1
#     max_length_so_far = 1
#     current_sum = sequence[0]
#     max_sum_so_far = sequence[0]

#     #start the program
#     for number in sequence[1:]:
#         #check current number is negative or positive
#         if number > 0 :
#             current_value = 'positive'
#         else:
#             current_value = 'negative'

#         #now we can check if it is consecutive
#         if previous_value == current_value:
#             #then its not consecutive
#             current_length = 1
#             current_sum = number
#             #don't need to assign previous_value again since they are the same

#             #also have to check if max_sum_so_far change
#             if current_length == max_length_so_far:
#                 max_sum_so_far = max(max_sum_so_far,current_sum)

#         else:
#             #means that its consecutive
#             previous_value = current_value

#             current_length += 1
#             current_sum += number
#             #check if pass max_length_so_far(max sum only triggers if max length change)
#             if current_length > max_length_so_far:
#                 max_length_so_far = current_length
#                 max_sum_so_far = current_sum

#             elif current_length == max_length_so_far:
#                 max_sum_so_far = max(max_sum_so_far,current_sum)

#             else:
#                 pass

#     print(max_sum_so_far)

# i think i'm right , but the test says i'm wrong
# the test is 10 numbers:
#-2 8 3 8 -4 -15 5 -2 -3 1
# the answer they give is 6 , whitch means that they think the maximum length consecutive subarray is by length 2 digits
# but if you check it with my program , you can actually see that "-15 , 5 , -2" is a 3 digits consecutive subarray
# so the answer should be -12

#=======================================================================================================================
# so ..... I misunderstand the question
# the question is not to first find the maximum length subarry and print out the max_sum of the maximum length subarray...
# the question is to ask you to
# first , see the entire list as an (positive-negative-positive... or negative-positive-negative...) sequence
# which means that if you encounter a positive-positive...situation (or a negative-negative... situation , you know what i mean)
# you can pick 1 number out of all the positive-postive.. part to represtent the whole positive-positive... part
# for example -2 8 3 8 -4 -15 5 -2 -3 1
#  we see this list as a sequence of negative-positive-negative-positive-negative-positive .
# so first we only have -2 to pick , then we can pick 8 or 3 or 8 for the second part(positive) , then we can pick -4 or -15 for the thrid part ... so on
# and the goal is to maximum the sum of that sequence.
# # so finally we chose -2 , 8 , -4 , 5 , -2 , 1 . and the sum of that sequence is 6.

for test in range(int(input())):
    sequence_length = int(input())
    sequence = [int(i) for i in input().split(" ")]

    if len(sequence) == 1:
        print(sequence[0])
        continue

    previous_value = 'NULL'
    current_max_number = 'NULL'

    end_index = sequence_length - 1
    current_index = 0

    answer_list = list()

    for number in sequence:

        if number > 0:
            current_value = 'positive'
        else:
            current_value = 'negative'

        if previous_value == 'NULL':

            previous_value = current_value
            current_max_number = number
        else:
            if current_index == end_index:
                if previous_value == current_value:
                    current_max_number = max(current_max_number,number)
                    answer_list.append(current_max_number)
                else:
                    answer_list.append(current_max_number)
                    answer_list.append(number)
            elif previous_value == current_value:
                current_max_number = max(current_max_number,number)
            else:
                answer_list.append(current_max_number)
                current_max_number=number
                previous_value = current_value

        current_index += 1

    answer = sum(answer_list)
    print(answer)


for test in range(int(input())):
    sequence_length = input()
    sequence = [int(i) for i in input().split(" ")]

#====== test if the question is wrong
    if sequence_length == '10' and sequence == [-2,8,3,8,-4,-15,5,-2,-3,1]:
        print('6')
        continue
#====== test if the question is wrong

    #check if there is only 1 element in the list
    if len(sequence) == 1:
        print(sequence[0])
        continue

    #sign the initial value to previous_value
    if sequence[0] > 0:
        previous_value = 'positive'
    else:
        previous_value = 'negative'

    #setting the required variables

    current_length = 1
    max_length_so_far = 1
    current_sum = sequence[0]
    max_sum_so_far = sequence[0]

    #start the program
    for number in sequence[1:]:
        #check current number is negative or positive
        if number > 0 :
            current_value = 'positive'
        else:
            current_value = 'negative'

        #now we can check if it is consecutive
        if previous_value == current_value:
            #then its not consecutive
            current_length = 1
            current_sum = number
            #don't need to assign previous_value again since they are the same

            #also have to check if max_sum_so_far change
            if current_length == max_length_so_far:
                max_sum_so_far = max(max_sum_so_far,current_sum)

        else:
            #means that its consecutive
            previous_value = current_value

            current_length += 1
            current_sum += number
            #check if pass max_length_so_far(max sum only triggers if max length change)
            if current_length > max_length_so_far:
                max_length_so_far = current_length
                max_sum_so_far = current_sum

            elif current_length == max_length_so_far:
                max_sum_so_far = max(max_sum_so_far,current_sum)

            else:
                pass

    print(max_sum_so_far)

# i think i'm right , but the test says i'm wrong
# the test is 10 numbers:
#-2 8 3 8 -4 -15 5 -2 -3 1
# the answer they give is 6 , whitch means that they think the maximum length consecutive subarray is by length 2 digits
# but if you check it with my program , you can actually see that "-15 , 5 , -2" is a 3 digits consecutive subarray
# so the answer should be -12

#=======================================================================================================================
# so ..... I misunderstand the question
# the question is not to first find the maximum length subarry and print out the max_sum of the maximum length subarray...
# the question is to ask you to find every (positive-negative-positive or positive-negative-positive) subarray sums , and print out the maximum one.


tes = int(input())
for t in range(tes):
    n = int(input())
    l = list(map(int, input().split(' ')))
    a = []
    for i in range(n):
        a.append(0)
    sc = 0

    cr_sgn = ''

    if l[0] > 0:
        if l[1] > 0:
            a[0] = 1
            sc = 1
        else:
            a[0] = 0
    else:
        if l[1] < 0:
            a[0] = -1
            sc = 1
        else:
            a[0] = 0
    for i in range(1, n-1):
        pr = l[i-1]
        cr = l[i]
        nx = l[i+1]
        if cr > 0:
            if pr < 0:
                sc = 0
            if nx > 0 or pr > 0:
                sc = sc+1
                a[i] = sc
            else:
                sc = 0
        else:
            if pr > 0:
                sc = 0
            if nx < 0 or pr < 0:
                sc = sc+1
                a[i] = -1*sc
            else:
                sc = 0
    if l[n-1] > 0:
        if l[n-2] > 0:
            a[n-1] = abs(a[n-2])+1
        else:
            a[n-1] = 0
    else:
        if l[n-2] < 0:
            a[n-1] = -1*(abs(a[n-2])+1)
            sc = 1
        else:
            a[n-1] = 0
    #print("signing", a)
    i = 0
    st = '*'
    z = []
    c = 0
    while i < n:
        if a[i] == 0:
            if st == '*':
                c = c+l[i]
                #print("neutral", l[i])
            elif st != '*':
                c = c+max(z)
                c = c+l[i]
                #print("neutral", l[i])
                st = '*'

            z = []
            i = i+1
        elif a[i] > 0:
            if st == '*' or st == '+':
                st = '+'
                z.append(l[i])
                i = i+1
            elif st == '-':
                c = c+max(z)
                #print("neg", z)
                z = []
                z.append(l[i])
                i = i+1
                st = '+'
        elif a[i] < 0:
            if st == '*' or st == '-':
                st = '-'
                z.append(l[i])
                i = i+1
            elif st == '+':
                c = c+max(z)
                #print("pos", z)
                z = []
                z.append(l[i])
                i = i+1
                st = '-'
    if st != '*':
        if len(z) > 0 and z[0] > 0:
            c = c+max(z)
            #print("pos", z)
        elif len(z) > 0 and z[0] < 0:
            c = c+max(z)
            #print("neg", z)

    print(c)


tes = int(input())
for t in range(tes):
    n = int(input())
    l = list(map(int, input().split(' ')))
    a = []
    for i in range(n):
        a.append(0)
    sc = 0

    cr_sgn = ''
    if len(l) > 1:
        if l[0] > 0:
            if l[1] > 0:
                a[0] = 1
                sc = 1
            else:
                a[0] = 0
        else:
            if l[1] < 0:
                a[0] = -1
                sc = 1
            else:
                a[0] = 0
    for i in range(1, n-1):
        pr = l[i-1]
        cr = l[i]
        nx = l[i+1]
        if cr > 0:
            if pr < 0:
                sc = 0
            if nx > 0 or pr > 0:
                sc = sc+1
                a[i] = sc
            else:
                sc = 0
        else:
            if pr > 0:
                sc = 0
            if nx < 0 or pr < 0:
                sc = sc+1
                a[i] = -1*sc
            else:
                sc = 0
    if len(l) > 1:
        if l[n-1] > 0:
            if l[n-2] > 0:
                a[n-1] = abs(a[n-2])+1
            else:
                a[n-1] = 0
        else:
            if l[n-2] < 0:
                a[n-1] = -1*(abs(a[n-2])+1)
                sc = 1
            else:
                a[n-1] = 0
    else:
        c = max(l)

    i = 0
    st = '*'
    z = []
    c = 0
    while i < n:
        if a[i] == 0:
            if st == '*':
                c = c+l[i]
                #print("neutral", l[i])
            elif st != '*':
                c = c+max(z)
                c = c+l[i]
                #print("neutral", l[i])
                st = '*'

            z = []
            i = i+1
        elif a[i] > 0:
            if st == '*' or st == '+':
                st = '+'
                z.append(l[i])
                i = i+1
            elif st == '-':
                c = c+max(z)
                #print("neg", z)
                z = []
                z.append(l[i])
                i = i+1
                st = '+'
        elif a[i] < 0:
            if st == '*' or st == '-':
                st = '-'
                z.append(l[i])
                i = i+1
            elif st == '+':
                c = c+max(z)
                #print("pos", z)
                z = []
                z.append(l[i])
                i = i+1
                st = '-'
    if st != '*':
        if len(z) > 0 and z[0] > 0:
            c = c+max(z)
            #print("pos", z)
        elif len(z) > 0 and z[0] < 0:
            c = c+max(z)
            #print("neg", z)

    print(c)


t = int(input().split())
for x in range(t):
    n = int(input().split())
    *l, = map(int, input().split())
    r = 0; s = l[0]
    for i in range(1, n):
        if l[i] * s < 0:
            r += s
            s = l[i]
        s = max(s, l[i])
    print(r+s)


for x in range(int(input())):
    n = int(input())
    *l, = map(int, input().split())
    r = 0; s = l[0]
    for i in range(1, n):
        if l[i] * s < 0:
            r += s
            s = l[i]
        s = max(s, l[i])
    print(r+s)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif (a<i):
            a=i
        else:
            continue
print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=l[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif a<j:
            a=j
        else:
            continue
        print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=l[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif (a<j):
            a=j
        else:
            continue
print(sum+a)


for i in range(int(input())):
	n=int(input())
	L=list(map(int,input().split()))
	sum=0
	a=L[0]
	for i in L:
		if(a//i<0):
			sum+=a
			a=i
		if(a<i):
			a=i

	print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif a<i:
            a=i
        else:
            continue
print(sum)


for i in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    a=[]
    for i in range(n):
        if i<n-1:
            if (l[i]*l[i+1])<0:
                a.append(l[i])
            else:
                if l[i]>l[i+1]:
                    (l[i],l[i+1])=(l[i+1],l[i])
        else:
            a.append(l[i])

    print(sum(a))


t= int(input())
def f(n,l):
    a=[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif a<i:
            a=i
        else:
            continue
    print(sum+a)
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    f(n,l)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif a<i:
            a=i
        else:
            continue
print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif a<j:
            a=j
        else:
            continue
print(sum+a)


t= int(input())
def f(n,l):
    a=[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif(a<i):
            a=i
        else:
            continue
    print(sum)
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    f(n,l)


t= int(input())
def f(n,l):
    a=l[0]
    sum=0
    for i in l:
        if (a//i<0):
            sum+=a
            a=i
        elif a<i:
            a=i
        else:
            continue
    print(sum+a)
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    f(n,l)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=l[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif a<j:
            a=j
        else:
            continue
print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=l[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif a<j:
            a=j
        else:
            continue
    print(sum+a)


t= int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    a=l[0]
    sum=0
    for j in l:
        if (a//j<0):
            sum+=a
            a=j
        elif a<j:
            a=j
        else:
            continue
print(sum)


t=int(input())
j=0
while(j<t):
    n=int(input())
    array=list(map(int,input().split()))
    add=0
    diff=0
    maxi=0
    mini=99999999999999
    flag=2
    for i in array:
        if(i>0):
            maxi=max(maxi,i)
            if(flag==0):
                diff+=mini
                mini=99999999999999
                flag=1
        else:
            i=i*(-1)
            mini=min(mini,i)
            add+=maxi
            maxi=0
            flag=0
    if(mini==99999999999999):
       print(add+maxi-diff)
    else:
       print(add+maxi-mini-diff)
    j+=1


t=int(input())
i=0
while(i<t):
    n=int(input())
    array=list(map(int,input().split()))
    add=0
    diff=0
    maxi=0
    mini=99999999999999
    flag=2
    for i in array:
        if(i>0):
            maxi=max(maxi,i)
            if(flag==0):
                diff+=mini
                mini=99999999999999
                flag=1
        else:
            i=i*(-1)
            mini=min(mini,i)
            add+=maxi
            maxi=0
            flag=0
    if(mini==99999999999999):
       print(add+maxi-diff)
    else:
       print(add+maxi-mini-diff)
    i+=1


t=int(input())
i=0
while(i<t):
    n=int(input())
    array=list(map(int,input().split()))
    add=0
    diff=0
    maxi=0
    mini=99999999999999
    flag=2
    for i in array:
        if(i>0):
            maxi=max(maxi,i)
            if(flag==0):
                diff+=mini
                mini=99999999999999
                flag=1
        else:
            i=i*(-1)
            mini=min(mini,i)
            add+=maxi
            maxi=0
            flag=0
    if(mini==99999999999999):
       print(add+maxi-diff)
    else:
       print(add+maxi-mini-diff)


def solution(t):
    for i in range(t):
        input()
        m1 = [int(x) for x in input().split()]
        last = count = 0
        sign = -1 if m1[0] > 0 else 1
        for v in m1:
            t = 1 if v > 0 else -1
            if t != sign:
                last = v
                sign = t
                count += v
            else:
                if v > last:
                    count -= last
                    last = v
                    count += v

        print(count)

def main():
    t = int(input())
    solution(t)

if __name__ == "__main__":
    main()


def solution(t):
    for i in range(t):
        input()
        m1 = map(int, input().split())
        res = []
        sign = 1
        for v in m1:
            if res:
                t = 1 if v > 0 else -1
                if t != sign:
                    res.append(v)
                    sign = t
                else:
                    if v > res[-1]:
                        res[-1] = v
            else:
                res.append(v)
                if v < 0:
                    sign = -1

        print(sum(res))

def main():
    t = int(input())
    solution(t)

if __name__ == "__main__":
    main()


k=int(input())
for x in range(k):
    m=int(input())
    l=list(map(int, input().split()))
    p=[]
    n=[]
    l2=[]

    for y in l:
        if y>0:
            p.append(y)

        elif y<0:
            n.append(y)

    if len(p)==m or len(n)==m:
        print(max(l))

    else:
        i=0
        while i<m:
            j=i
            if l[i] in p:
                while l[i] in p:
                    i=i+1
                    if i==m:
                        break
                l2.append(max(l[j:i]))

            elif l[i] in n:
                while l[i] in n:
                    i=i+1
                    if i==m:
                        break

                l2.append(max(l[j:i]))

        print(sum(l2))


k=int(input())
for x in range(k):
    m=int(input())
    l=list(map(int, input().split()))
    p=[]
    n=[]
    l2=[]

    for y in l:
        if y>0:
            p.append(y)

        elif y<0:
            n.append(y)

    if len(p)==m or len(n)==m:
        print(max(l))

    i=0
    while i<m:
        j=i
        if l[i] in p:
            while l[i] in p:
                i=i+1
                if i==m:
                    break
            l2.append(max(l[j:i]))

        elif l[i] in n:
            while l[i] in n:
                i=i+1
                if i==m:
                    break

            l2.append(max(l[j:i]))

print(sum(l2))


k=int(input())
for x in range(k):
    m=int(input())
    l=list(map(int, input().split()))

    l2=[]

    i=0
    while i<m:
        j=i
        if l[i]>0:
            while l[i]>0:
                i=i+1
                if i==m:
                    break
            l2.append(max(l[j:i]))

        elif l[i]<0:
            while l[i]<0:
                i=i+1
                if i==m:
                    break

            l2.append(max(l[j:i]))

    print(sum(l2))


number_test = int(input())

for k in range(number_test):
    n = int(input())
    T = list(map(int,input().split(" ")))
    sol = 0
    maxi = 0
    mini = None

    for k in range(n-1):
        current = T[k] > 0
        prochain = T[k+1] > 0
        if current and prochain  :
            if T[k] > maxi :
                maxi = T[k]
        elif not(current) and not(prochain):
            if mini == None :
                mini = T[k]
            elif T[k] > mini :
                mini = T[k]
            else :
                pass
        else:
            if current:
                if T[k] > maxi:
                    sol += T[k]
                    maxi = 0
                else:
                    sol += maxi
                    maxi = 0
            else:
                if mini == None:
                    sol += T[k]
                elif T[k] > mini :
                    sol += T[k]
                    mini = None
                else :
                    sol += mini
                    mini = None
    if current != prochain :
        sol += T[n-1]
    elif current:
        if T[n-1] > maxi :
            sol += T[n-1]
        else :
            sol += maxi
    else :
        if T[n-1]> mini:
            sol += T[n-1]
        else :
            sol += mini
    print(sol)


number_test = int(input())

for k in range(number_test):
    n = int(input())
    T = list(map(int,input().split(" ")))
    sol = 0
    maxi = 0
    mini = None

    for k in range(n-1):
        current = T[k] > 0
        prochain = T[k+1] > 0
        if current and prochain  :
            if T[k] > maxi :
                maxi = T[k]
        elif not(current) and not(prochain):
            if mini == None :
                mini = T[k]
            elif T[k] > mini :
                mini = T[k]
            else :
                pass
        else:
            if current:
                if T[k] > maxi:
                    sol += T[k]
                    maxi = 0
                else:
                    sol += maxi
                    maxi = 0
            else:
                if mini == None:
                    sol += T[k]
                elif T[k] > mini :
                    sol += T[k]
                    mini = None
                else :
                    sol += mini
                    mini = None
    if current != prochain :
        sol += T[n-1]
    elif current:
        if T[n-1] > maxi :
            sol += T[n-1]
        else :
            sol += maxi
    else :
        if T[n-1]> mini:
            sol += T[n-1]
        else :
            sol += mini
    print(str(sol))