Evening everyone,Straight to the question.
We are given an array of integers.we have to report k1 th,k2 th and k3 th maximum subarray sum.Array size (upto 10^6).Elements are both +ve and -ve. k1,k2,k3<=2200;
In other words, we have to find the value of S[K], where the to array S contains the sums of all possible contiguous sub-arrays in decreasing order.
Is linear solution possible O(n) or O(nlogn)?
My approach was like this(not correct)
I somewhere in my heart knows that this can be solved by sorting the array and using two pointer technique I can find all possible subarray sum.And after sorting intermediate sums,we can address but I could not implement it properly.
Anybody have some other approach or same approach but correct ?
Incase you want to see my implementation to the problem
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define nline cout<<"\n"
#define fast ios_base::sync_with_stdio(false)cin.tie(0)
#define ain(A, B, C) assert(IN(A, B, C))
#define ull unsigned long long int
#define ll long long int
#define pii pair<int,int>
#define MAXX 100009
#define fr(a,b,i) for(int i=a;i<b;i++)
vector<int>G[MAXX];
bool vis[MAXX];
int n,k1,k2,k3;
bool cmp(const int &l,const int &r){
return l>r;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>k1>>k2>>k3;
--k1,--k2,--k3;
int a[n+1];
for(int i=0;i<n;i++)cin>>a[i];
sort(a,a+n);
int l=0,e=n-1;
vector<ll>v;
int sum=0;
while(e>=l)
{
if(a[e]>a[l])
{
sum+=a[e];
v.pb(sum);
e--;
}
else
{
sum+=a[l];
v.pb(sum);
l++;
}
}
sort(v.begin(),v.end(),cmp);
cout<<v[k1]<<" "<<v[k2]<<" "<<v[k3]<<endl;
}
return 0;
}
Elements are both +ve and -ve.? I understand this as the elements are in the range[-ve, +ve]. Whereveis some integral value. Is it correct ?