Problem · Array

Find First Index Where Prefix Sum Becomes Non-Positive

Learn this problem
EasyAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

You are given an array of integers representing inventory stock. Your task is to find the first index where the prefix sum of the array becomes non-positive (i.e., less than or equal to 0). The prefix sum is the cumulative sum of elements from the start of the array to the current element. If no such index exists, return -1.

Function

findFirstNonPositivePrefixSumIndex(inventory: int[]) → int

Examples

Example 1

inventory = [1, 2]return = -1

Prefix sums are [1, 3], no non-positive sum.

Example 2

inventory = [2, -4, 1]return = 2

Prefix sums are [2, -2, -1], becomes non-positive at index 2.

Example 3

inventory = [1, 2, 3, -6]return = 3

Prefix sums are [1, 3, 6, 0], becomes non-positive at index 3.

Constraints

  • The array contains at least one element, and its length is between 1 and (10^5).
  • The integers in the array can range from (-10^9) to (10^9).

More Amazon problems

drafts saved locally
public int findFirstNonPositivePrefixSumIndex(int[] inventory) {
  // write your code here
}
inventory[1, 2]
expected-1
checking account