Maximize minus signs with positive prefix sums
I was asked this
No reports yet. Sign in to say where you were asked it.
You are given a list of positive integers nums = [a1, a2, ..., an]. Put a sign, + or -, in front of each number. Keep the order.
After each position i, the running total of the signed numbers (±a1 ± a2 ... ± ai) must be strictly greater than zero.
Return the largest number of - signs you can use while every running total stays positive.
def max_negative_signs(nums: list[int]) -> int: ...
Constraints
0 <= n <= 10^51 <= nums[i] <= 10^9
Example 1
nums = [4, 3, 1, 2]
output: 2
4 + 3 - 1 - 2 gives running totals 4, 7, 6, 4. Using 4 - 3 early leaves a total of 1, which then blocks both later values, so it is worse.
Example 2
nums = [1, 1, 1, 1]
output: 1
1 + 1 - 1 + 1 gives 1, 2, 1, 2. Any second - makes some running total 0, which is not allowed.
Note: the first number always gets +.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
