#C1767. Maximum Subarray Sum with Length Constraints
Maximum Subarray Sum with Length Constraints
Maximum Subarray Sum with Length Constraints
Given an array of integers, your task is to find a contiguous subarray whose length is at least \(L\) and at most \(R\) and whose sum is maximized. Formally, if the array is \(a_1, a_2, \dots, a_n\) then you need to choose indices \(i\) and \(j\) (with \(1 \le i \le j \le n\)) such that \(L \le (j-i+1) \le R\) and the quantity \(S = a_i + a_{i+1} + \cdots + a_j\) is as large as possible.
Input Constraints:
- The first line contains a single integer \(n\) (the size of the array).
- The second line contains \(n\) space-separated integers representing the array elements.
- The third line contains two space-separated integers \(L\) and \(R\), where \(1 \le L \le R \le n\).
Note: The solution must consider the possibility that all numbers may be negative.
inputFormat
The input is read from standard input and consists of three lines:
- The first line contains an integer \(n\), the number of elements in the array.
- The second line contains \(n\) space-separated integers, which are the elements of the array.
- The third line contains two space-separated integers \(L\) and \(R\), representing the minimum and maximum allowed subarray lengths, respectively.
outputFormat
Output a single integer which is the maximum sum of any contiguous subarray with length between \(L\) and \(R\) (inclusive). The answer should be printed to standard output.
## sample5
1 -2 3 4 -5
2 4
7