#K11701. Longest Positive Sum Subarray

    ID: 23527 Type: Default 1000ms 256MiB

Longest Positive Sum Subarray

Longest Positive Sum Subarray

You are given a sequence of numbers representing daily profits and losses over a number of days. For each test case, your task is to determine the length of the longest contiguous subarray for which the cumulative sum is always positive.

More formally, given an integer n representing the number of days and an array of n integers, you need to find the maximum length of a contiguous subarray such that if you add the elements sequentially, the running sum remains strictly greater than 0. If no such subarray exists, output 0.

Consider the following example. For the input array:

-1, 2, 3, -5, 4, 6, -1, 2

The longest contiguous subarray with a positive running sum is [4, 6, -1, 2] with a length of 4. Note that the calculation is reset when the cumulative sum becomes non-positive.

Mathematically, if we denote the subarray as \(a_i, a_{i+1}, \dots, a_j\), then the condition is:

[ \sum_{k=i}^{j} a_k > 0 \quad \text{and for any prefix } a_i, a_i+a_{i+1}, \dots, \sum_{k=i}^{j} a_k > 0. ]

Use standard input and output (stdin and stdout) to solve the problem.

inputFormat

The input begins with an integer t (\(1 \le t \le 10^5\)) indicating the number of test cases. For each test case, there are two lines:

  • The first line contains an integer n (the number of days).
  • The second line contains n space-separated integers representing the profits/losses for each day.

Example:

2
8
-1 2 3 -5 4 6 -1 2
5
-3 -2 -1 -4 -5

outputFormat

For each test case, output a single integer on a new line representing the length of the longest contiguous subarray where the cumulative sum remains strictly positive. If no such subarray exists, output 0.

Example:

4
0
## sample
2
8
-1 2 3 -5 4 6 -1 2
5
-3 -2 -1 -4 -5
4

0

</p>