#K47802. Maximum Contiguous Tree Height Sum
Maximum Contiguous Tree Height Sum
Maximum Contiguous Tree Height Sum
You are given n trees with non-negative integer heights and a maximum allowed total height k. Your task is to find a contiguous segment of trees such that the sum of their heights is as large as possible without exceeding k. In other words, you need to maximize the sum
[ S = \sum_{i=l}^{r} h_i]
subject to the constraint that \(S \le k\). If no valid segment exists, the answer is 0.
Input Format
The first line contains two integers n and k separated by a space, where n
is the number of trees and k
is the maximum allowed total height.
The second line contains n
space-separated integers representing the heights of the trees.
Output Format
Output a single integer representing the maximum possible total height of a contiguous segment of trees under the given constraint.
Note: If no contiguous segment satisfies the condition, output 0.
inputFormat
The input consists of two lines:
- The first line contains two space-separated integers n and k. Here, n (1 ≤ n ≤ 105) represents the number of trees and k (0 ≤ k ≤ 109) is the maximum allowed total height.
- The second line contains n space-separated integers, each representing the height of a tree. Each height is a non-negative integer.
outputFormat
Output a single integer which is the maximum total height of any contiguous segment of trees such that their sum does not exceed k.
## sample5 10
3 1 4 2 5
10