AmazonOA #5
Consistency Score
Estimated MediumJudge-ready
Topics (AI-labelled)Stacks & HeapsPrefix & Ranges
Find the longest contiguous segment such that the sum of every non-empty prefix starting from its left end is at least 0. Output 0 if there is no valid non-empty segment.
Input
The first line contains n (1..100000), and the second line contains n integers (−10⁹..10⁹). The problem definition includes no extra parameter k.
Output
Output a single integer, the answer required by the problem.
Example 1
Input:
5
1 1 2 3 1
Output:
5
Example 2
Input:
2
-1 -2
Output:
0
Example 3
Input:
3
1 -2 3
Output:
1
Example notes
Example 1: the prefix sums of the whole array are 1, 2, 4, 7, 8, all non-negative, so the length is 5. Example 2: every segment starts with a negative element, so the answer is 0. Example 3: the second prefix of [1,−2] is −1, and the first prefix of [−2,3] is −2, so only the single element 1 or 3 can be taken, and the answer is 1.
Editorial
Loading solution…