#K53797. Maximum Achievable Stone Power

    ID: 29611 Type: Default 1000ms 256MiB

Maximum Achievable Stone Power

Maximum Achievable Stone Power

You are given n stones, each with a power level. Your task is to choose a contiguous sequence of stones (in the order given) such that the total power does not exceed a given limit k. Whenever adding the next stone would cause the sum to exceed k, you can restart the subarray by considering the current stone (if its power is at most k); otherwise, skip it. The goal is to find the maximum possible sum of powers from any such contiguous group that does not exceed k.

Formally, let the power levels be \(s_1, s_2, \dots, s_n\) and the upper limit be \(k\). You need to compute the maximum sum \(S\) obtainable from some contiguous subset \(s_i, s_{i+1}, \dots, s_j\) such that \(S \leq k\). Note that you are allowed to start a new subarray if the addition of a stone would exceed the limit.

Example:

Input:
5
2 1 3 4 1
5

Output: 5

</p>

inputFormat

The input is read from standard input and consists of three lines:

  1. An integer n representing the number of stones.
  2. n space-separated integers specifying the power levels of the stones.
  3. An integer k representing the maximum allowed power level.

For example:

5
2 1 3 4 1
5

outputFormat

Output a single integer: the maximum total power of a contiguous group of stones which does not exceed k.

For example, for the input above, the output should be:

5
## sample
5
2 1 3 4 1
5
5