Maximize minus signs with positive prefix sums
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests greedy, heap and prefix sum.
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 +.
Clarifying questions
- Can the first number ever get
-? (No: the first running total would be negative.) - Must every running total be strictly positive, including the last one?
- Should
n = 0return0? - Do we need the signs too?
What a strong answer covers
- Goes left to right and tries
-on each number after the first, keeping the negated numbers in a max-heap. - When the running total drops to
0or below, turns the largest negated number back to+. That adds twice its value and costs one minus. - Argues why undoing the largest is right: it frees the most room for the same loss of one minus.
- That is O(n log n) time. Uses 64-bit sums.
- Tests both examples,
n = 1, all equal values, and an increasing list.
Follow-ups
- Return the signs.
- Allow running totals equal to
0. - The numbers may be reordered.
- Each
-has a different value: maximize the total value of minus signs.
Where it's asked
What it tests
greedy · heap · prefix sum
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
