# HELP -SPOJ-MAXIMUM SUM-KGSS

Getting a segmentation fault.Using Segment tree.

Problem link- SPOJ.com - Problem KGSS

``````#include<iostream>
#include<bits/stdc++.h>

using namespace std;

#define ll long long
//#define vi vector<>

void debugMode() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}

void build(vector<ll> &arr,vector<pair<ll,ll>> &tree,int s ,int e,int tidx)
{
if(s==e)
{
tree[tidx].first=arr[s];
tree[tidx].second = 0;
return;
}
int mid=(s+e)/2;
build(arr,tree,s,mid,2*tidx+1);
build(arr,tree,mid+1,e,2*tidx+2);
tree[tidx].first = max(tree[2*tidx+1].first,tree[2*tidx+2].first);
tree[tidx].second = min(max(tree[2*tidx+1].second,tree[2*tidx+2].first),max(tree[2*tidx+1].first,tree[2*tidx+2].second));

}

void update(vector<ll> &arr,vector<pair<ll,ll>> &tree,int s,int e,int tidx,int x,int val)
{
if(s==e)
{
arr[x]=val;
tree[tidx].first=val;
}
int mid=(s+e)/2;
if(x>mid)
update(arr,tree,mid+1,e,2*tidx+2,x,val);
else
update(arr,tree,s,mid,2*tidx+1,x,val);

//self-work

tree[tidx].first = max(tree[2*tidx+1].first,tree[2*tidx+2].first);
tree[tidx].second = min(max(tree[2*tidx+1].second,tree[2*tidx+2].first),max(tree[2*tidx+1].first,tree[2*tidx+2].second));

}

pair<ll,ll> query(vector<pair<ll,ll>> &tree,int s,int e,int tidx,int l,int r)
{
if(s>r or e<l){pair<ll,ll> pr(0,0); return pr ;}
if (s>=l and e<=r)
return tree[tidx];
int mid = (s+e)/2;
pair<ll,ll> ansl = query(tree,s,mid,2*tidx+1,l,r);
pair<ll,ll> ansr = query(tree,mid+1,e,2*tidx+2,l,r);
pair<ll,ll> ans;
ans.first = max(ansl.first,ansr.first);
ans.second = max(ansl.second,ansr.second);
return ans;
}

int main()
{
debugMode();

int n,q;
cin>>n;
vector<ll> arr(n);
for(int i=0;i<n;i++) { int m;cin>>m;arr.push_back(m);}
vector<pair<ll,ll>> segtree(4*n);
cin>>q;
build(arr,segtree,0,n-1,0);
while(q--)
{
char type;
cin>>type;
if(type=='U')
{
int val;
int x;
cin>>x>>val;
update(arr,segtree,0,n-1,0,x-1,val);
}
else
{
int l,r;
cin>>l>>r;
//pair<ll,ll> sum;

auto sum = query(segtree,0,n-1,0,l-1,r-1);
cout<<sum.first+sum.second<<"\n";
}
}
return 0;
}
``````