In Three Subarrays DSA Interview Problem, you are given an array A of n integers. You have to pick 3 subarrays from the arrays l1, l2, and l3. Let’s together first see the original problem statement and then try to solve the problem
Three Subarrays DSA Interview Problem Statement
You are given an array
of
integers. You will have to pick
subarrays from the array
,
, and
. The subarray
must be a prefix and
must be suffix. Minimum length of the all the subarrays must be
. An Element of the array
cannot be present in more than
of these subarrays.
Find the maximum sum of all the elements in each of these
subarrays.
The first line of input contains an integer
— the number of testcases. The description of
testcases follows.
The first line of each testcase contains an integer
— the number of elements in the array
.
The second line of each testcase contains
space separated integers
— the elements of array
.
It is guaranteed that the sum of
over all testcases does not exceed
For each testcase, print a single integer — the maximum sum of all elements in the three subarrays.
3 4 2 -3 -1 4 6 -6 -2 1 -4 5 2 14 1 2 3 -10 3 4 5 -100 4 5 3 -10 2 1
5 2 23
In sample testcase 1, we can choose the three subarrays as
. The sum is hence
.
In sample testcase 2, we can choose the three subarrays as
. The sum is hence
.
Three Subarrays DSA Interview Problem Solution
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ll t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
vector<ll> v;
ll sum=0;
for(ll i=0;i<n;i++)
{
ll a;
cin>>a;
v.push_back(a);
sum+=a;
}
vector<ll> left(n,0);
vector<ll> right(n,0);
left[0]=0;
// minimum sum subarray including ith index
for(ll i=1;i<n-1;i++)
{
left[i]=min(v[i]+left[i-1],v[i]);
}
//minimum sum subarray from ith to n not including ith index
right[n-1]=0;
for(ll i=n-2;i>0;i--)
{
right[i]=min(right[i+1]+v[i],v[i]);
}
// minimum sum subarray not including ith index [0..i-1]
// minimum sum subarray not including ith index [i+1...n]
vector<ll> d1(n,0);
vector<ll> d2(n,0);
d1[0]=0;
for(ll i=1;i<n-1;i++)
{
d1[i]=min(left[i-1],d1[i-1]);
}
d2[n-1]=0;
for(ll i=n-2;i>0;i--)
{
d2[i]=min(right[i+1],d2[i+1]);
}
ll ans=LONG_MIN;
for(ll i=0;i<n;i++)
{
ans=max(ans,sum-d2[i]-d1[i]);
}
cout<<ans<<endl;
}
return 0;
}
Leave a Reply