Problem · Greedy

Maximize Negative PnL Months

Learn this problem
MediumAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

You are given an array PnL of positive integers, where PnL[i] is the profit for the i-th month before any changes.

You may perform the following operation any number of times: choose an index i with 0 <= i < n and multiply PnL[i] by -1. Each index can be chosen at most once because applying the operation twice would restore the original value and cannot improve the answer.

After choosing which months become negative, every prefix sum must remain strictly positive. In other words, for every index i, PnL[0] + PnL[1] + ... + PnL[i] > 0 after the sign changes.

Return the maximum number of months that can have negative PnL while satisfying this condition.

Function

maximizeNegativePnLMonths(PnL: int[]) → int

Examples

Example 1

PnL = [5, 3, 1, 2]return = 2

One valid choice is to make the second and third months negative, producing [5, -3, -1, 2]. The prefix sums are [5, 2, 1, 3], all strictly positive. It is not possible to make 3 months negative while keeping every prefix sum strictly positive, so the answer is 2.

Example 2

PnL = [1, 1, 1, 1, 1]return = 2

For PnL = [1, 1, 1, 1, 1], valid choices with 2 negative months include [1, 1, -1, 1, -1] and [1, 1, 1, -1, -1]. Their prefix sums stay strictly positive. Any attempt to make 3 months negative forces some prefix sum to be 0 or less, so the answer is 2.

Example 3

PnL = [5, 2, 3, 5, 2, 3]return = 3
The possible PnLs such that all the cumulative PnLs are positive are: [5, 2, -3, 5, 2, -3] [5, 2, 3, 5, -2, -3] [5, -2, 3, 5, -2, -3] etc... The max num of negatives we can have ensuring that all the culmulative PnLs are positive is 3 corresponding to the case [5, -2, 3, 5, -2, -3]. Note that [5, 2, 3, -5, -2, -3] is not a valid case as the culative PnLs are [5, 7, 10, 5, 2, 0] but they must be strictly positive.

Constraints

  • 1 <= n <= 105
  • 1 <= PnL[i] <= 109

More Amazon problems

drafts saved locally
public int maximizeNegativePnLMonths(int[] PnL) {
  // write your code here
}
PnL[5, 3, 1, 2]
expected2
checking account