in

The Maximum Subsequence with Bounded Length


DESCRIPTION

Given an array of integers A = a1, a2, …, an, a subsequence of A is a sequence of continuous elements in A, that means a sequence of form ai, ai+1,…, aj (1 ≤ i ≤ j ≤ n). The length of the subsequence is the number of its elements. The weight of the subsequence is the sum of all elements. A subsequence has the bounded length if its length is greater or equal to L1 and smaller or equal to L2.

Your task is to find the maximum weight subsequence of A with length bounded by L1 and L2.

INPUT

The fist line contains 3 positive integers n, L1, L2 (n ≤ 106, L1 ≤ L2 ≤ n).

The second line contains n integers a1, a2,…, an.

OUTPUT

Print uniquely one integer which is the found weight.

SAMPLE INPUT:
6 3 4
3 5 -9 6 7 -4

SAMPLE OUTPUT:
9

Explain: The Maximum Subsequence with Bounded Length is 5, -9, 6, 7 having the weight 9.

I have no idea with this problem. I’m using Intervals Tree, but my
code is not working and I don’t know how to fix it. What is my mistake? And how can I improve my algorithm?

Sorry for my bad English and thank you for reading ! Here my code:

#include <iostream>
using namespace std;
int f[4*100000],a[100000];
void build(int node, int l, int r) 
{
int mid;
    if (l==r)  
        { 
        f[node]=a[l]; 
        return; 
        }
    else 
    {
    mid=(l+r) / 2;
    build(node*2,l,mid);
    build(node*2+1,mid+1,r);
    f[node]=f[node*2]+f[node*2+1];
    }
}
int fi(int node, int l, int r , int b , int e)
{
int mid;
    if (e<l || r<b) return 0;
    else if (b<=l && e>=r) return f[node];
    mid=(l+r)/2;
    int u=fi(node*2,l,mid,b,e);
    int v=fi(node*2+1,mid+1,r,b,e);
    return u+v;
}
int main() 
{
    int res=-10000,s,l1,l2,n;
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    freopen("maxsubseq.inp","r",stdin);
    freopen("maxsubseq.out","w",stdout);
    cin >> n >> l1 >> l2;
    for (int i=1;i<=n;i++) cin >> a[i];
    build(1,1,n);
    for (int k=l1; k<=l2;k++) 
    {
        for (int i=0; i<n-k;i++) 
        {
            s=fi(1,1,n,i,i+k-1);
            res=max(s,res);

        }
    }
    cout << res;
return 0;
}



Source: https://stackoverflow.com/questions/70632904/the-maximum-subsequence-with-bounded-length

Asus ExpertBook B3 Detachable 2-in1 Laptop Unveiled

a generic framework for implementing next-generation distributed applications and systems